将图像文件转换为 numpy 数组时内存不足
Out of memory converting image files to numpy array
我正在尝试 运行 循环遍历图像文件夹和 returns 两个 numpy 数组:x - 将图像存储为numpy 数组 y - 存储标签。
一个文件夹可以轻松拥有超过 40.000 张尺寸为 (224,224) 的 rgb 图片。
我有大约 12Gb 的内存,但经过一些迭代后,使用的内存突然增加,一切都停止了。
我该怎么做才能解决这个问题?
def create_set(path, quality):
x_file = glob.glob(path + '*')
x = []
for i, img in enumerate(x_file):
image = cv2.imread(img, cv2.IMREAD_COLOR)
x.append(np.asarray(image))
if i % 50 == 0:
print('{} - {} images processed'.format(path, i))
x = np.asarray(x)
x = x/255
y = np.zeros((x.shape[0], 2))
if quality == 0:
y[:,0] = 1
else:
y[:,1] = 1
return x, y
您无法将那么多图像加载到内存中。您正在尝试将给定路径中的每个 文件 加载到内存,方法是将它们附加到 x.
尝试分批处理它们,或者如果您正在为 tensorflow 应用程序执行此操作,请尝试先将它们写入 .tfrecords。
如果您想节省一些内存,请将图像保留为 np.uint8 而不是将它们转换为浮动(当您在此行中对它们进行标准化时会自动发生 > x = x/255
)
您的 x.append(np.asarray(image))
行中也不需要 np.asarray
。 image
已经是一个数组。 np.asarray
用于将列表、元组等转换为数组。
编辑:
一个非常粗糙的批处理示例:
def batching function(imlist, batchsize):
ims = []
batch = imlist[:batchsize]
for image in batch:
ims.append(image)
other_processing()
new_imlist = imlist[batchsize:]
return x, new_imlist
def main():
imlist = all_the_globbing_here()
for i in range(total_files/batch_size):
ims, imlist = batching_function(imlist, batchsize)
process_images(ims)
我正在尝试 运行 循环遍历图像文件夹和 returns 两个 numpy 数组:x - 将图像存储为numpy 数组 y - 存储标签。
一个文件夹可以轻松拥有超过 40.000 张尺寸为 (224,224) 的 rgb 图片。 我有大约 12Gb 的内存,但经过一些迭代后,使用的内存突然增加,一切都停止了。
我该怎么做才能解决这个问题?
def create_set(path, quality):
x_file = glob.glob(path + '*')
x = []
for i, img in enumerate(x_file):
image = cv2.imread(img, cv2.IMREAD_COLOR)
x.append(np.asarray(image))
if i % 50 == 0:
print('{} - {} images processed'.format(path, i))
x = np.asarray(x)
x = x/255
y = np.zeros((x.shape[0], 2))
if quality == 0:
y[:,0] = 1
else:
y[:,1] = 1
return x, y
您无法将那么多图像加载到内存中。您正在尝试将给定路径中的每个 文件 加载到内存,方法是将它们附加到 x.
尝试分批处理它们,或者如果您正在为 tensorflow 应用程序执行此操作,请尝试先将它们写入 .tfrecords。
如果您想节省一些内存,请将图像保留为 np.uint8 而不是将它们转换为浮动(当您在此行中对它们进行标准化时会自动发生 > x = x/255
)
您的 x.append(np.asarray(image))
行中也不需要 np.asarray
。 image
已经是一个数组。 np.asarray
用于将列表、元组等转换为数组。
编辑:
一个非常粗糙的批处理示例:
def batching function(imlist, batchsize):
ims = []
batch = imlist[:batchsize]
for image in batch:
ims.append(image)
other_processing()
new_imlist = imlist[batchsize:]
return x, new_imlist
def main():
imlist = all_the_globbing_here()
for i in range(total_files/batch_size):
ims, imlist = batching_function(imlist, batchsize)
process_images(ims)