我正在尝试使用此代码来调整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]
是否有办法降低此调整大小的内存使用量
答案 0 :(得分:1)
uint
数组将需要超过8 GB的内存,因此非常期待OOM。但是,如果您确实需要这种尺寸的图像,则可以通过生成器功能即时调整其大小:
def resized_images_generator():
for image in train_images:
yield tf.image.resize(image, (244, 244))
答案 1 :(得分:0)
您正试图将全部60,000个调整大小的图像保留在内存中,这会导致资源耗尽错误。由于较大的图像中没有更多信息,因此不确定为什么要调整图像的大小。如果确实需要调整它们的大小,则可以将它们写入磁盘目录,然后再次读取它们。您不能同时读回所有内容,因为会遇到另一个资源耗尽错误。要调整大小并保存图像,请使用下面的代码
import cv2
import os
save_dir=r'c:\Temp\cifar\train'
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.