尝试规范化图像数组时出现 MemoryError

问题描述

我有一个文件夹,其中包含 110k 个图像,每个图像的形状为 (256,256,3)。我正在一一阅读,转换为 numpy 数组并存储在列表中。之后,我将列表转换为 numpy 数组。 numpy 数组的形状是 (110000,3)。然后,当我尝试使用 images = images / float(255) 对图像进行标准化时,会显示错误

 File "loading_images.py",line 25,in <module>
    images = images / float(255)
MemoryError: Unable to allocate 161. GiB for an array with shape (110000,3) and data type float64

有没有其他方法可以做到这一点?

我当前的代码是这样的:

files = glob.glob(dir + "*.png")
images = []
for f in files
    im = cv2.imread(f)
    img_arr = np.asarray(im)
    images.append(img_arr)

images = np.asarray(images)
images = images / float(255)
 

解决方法

认为你的问题是 cv2 给出了一个 int8(如果我错了,请纠正我),而你正试图将值转换为 float64 的

import numpy as np 
print(np.float64(255).itemsize)
print(np.int8(255).itemsize)

这意味着在类型转换之后,您剩下大约 8 倍的字节。您一开始有 110000×256×256×3=21GB 的图像数据,这可能正好在您的 RAM 限制范围内。转换为浮点数后,您将获得 8x21 = 168GB 的​​数据,这超出了我认识的任何人的 RAM 限制哈哈。

但这不是解决方案,您真的需要同时加载所有图像吗?