在张量流中调整图像大小时出现 OOM 错误



我正在尝试使用此代码从 Keras 调整 cifar10 中的图像大小

cifar10 = tf.keras.datasets.cifar10
(train_images, train_labels), (test_images, test_labels) = cifar10.load_data()
train_images = tf.image.resize(train_images, (244, 244))
test_images = tf.image.resize(test_images, (244, 244))

但是,当我使用 cpu 运行它时,我收到此错误消息

File "<string>", line 3, in raise_from
tensorflow.python.framework.errors_impl.ResourceExhaustedError: OOM when allocating tensor 
with shape[50000,244,244,3] and type float on /job:localhost/replica:0/task:0/device:CPU:0 
by allocator cpu [Op:ResizeBilinear]

无论如何可以降低此大小调整的内存使用

具有 shape[50000,244,244,3] 的uint数组将需要超过 8 GB 的内存,因此 OOM 是相当预期的。但是,如果您确实需要这种大小的图像,您可以通过生成器功能即时调整它们的大小:

def resized_images_generator():
for image in train_images:
yield tf.image.resize(image, (244, 244))

您正在尝试将整个 60,000 个调整大小的图像保留在内存中,这会导致资源耗尽错误。不确定为什么要调整图像大小,因为较大的图像中没有更多信息。如果您确实需要调整它们的大小,您将将它们写入磁盘目录,然后再次读取它们。您不能同时将它们全部读回去,因为您将获得另一个资源耗尽错误。要调整大小和保存图像,请使用以下代码

import cv2
import os
save_dir=r'c:Tempcifartrain'
if os.path.isdir(save_dir)==False:
os.mkdir(save_dir)
for i in range(train_images.shape[0] ):
file_name=save_dir + '\' +str(i) + '.jpg'     
resized = cv2.resize(train_images[i],(224,224), interpolation = cv2.INTER_AREA)     
status=cv2.imwrite(file_name, resized)```
do the same for the test_images. You can then read them in as needed.

最新更新