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

MemoryError when trying to normalize an array of images

我有一个文件夹,其中包含 110k 个图像,每个图像的形状为 (256, 256, 3)。我正在一个一个地阅读,转换成一个 numpy 数组并存储在一个列表中。之后,我将列表转换为 numpy 数组。 numpy 数组的形状是 (110000, 256, 256, 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, 256, 256, 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 限制之内。转换为float后,你得到8x21 = 168GB的数据,这超出了我认识的任何人的RAM限制哈哈。

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