Python列表对字典和OpenCV的理解

时间:2018-05-12 21:30:58

标签: python-3.x opencv dictionary list-comprehension

当我运行它时,Python会坐下来并在arr处永久占用。它只是慢慢消耗RAM而不做其他事情:

import os
import glob
import cv2

root = r'path\to\img'

files = glob.iglob( os.path.join(root,'*.jpg') )

arr = [ { 'img_nm' : fl,
          'img' : cv2.imread( fl ) } for fl in files ]

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

这个loop comprehension将一次构建整个数据集。

arr = [ { 'img_nm' : fl,
          'img' : cv2.imread( fl ) } for fl in files ]

因此,对于漫长的处理,运行需要很长时间,并将整个结果同时存储在内存中。更好的方法是一次一个地处理每个图像,例如:

for fl in glob.iglob( os.path.join(root,'*.jpg') ):
    new_image_record = { 
        'img_nm' : fl,
        'img' : cv2.imread( fl )
    }
    # save new record