这是代码的核心:
import numpy as np
def float_im(img):
return np.divide(img, 255.)
# adapted from: https://stackoverflow.com/a/52463034/9768291
def random_crop(images):
print("Started randomly cropping HR images")
crop_h, crop_w = img_width, img_height
y = []
i = -1 # To begin with 0
for img in images:
if (img.shape[0] >= crop_h) and (img.shape[1] >= crop_w):
print(i + 1, "images processed")
#img = rgb2ycbcr(img) # TODO: switch from RGB channels to CbCrY
for _ in range(crops_p_img):
# Cropping a random part of the image
rand_h = np.random.randint(0, img.shape[0]-crop_h)
rand_w = np.random.randint(0, img.shape[1]-crop_w)
tmp_img = img[rand_h:rand_h+crop_h, rand_w:rand_w+crop_w]
# Saving the images
i += 1
initial_image = save_np_img(tmp_img, y_data_path, str(i) + ".png")
y.append(float_im(initial_image)) # From [0,255] to [0.,1.]
# Augmenting the image TODO: look into integrating "imgaug" library
if augment_img:
# Vertical axis flip
i += 1
tmp_img = np.fliplr(initial_image)
y.append(float_im(save_np_img(tmp_img, y_data_path, str(i) + ".png")))
# Horizontal axis flip of tmp_img
i += 1
y.append(float_im(save_np_img(np.flipud(tmp_img), y_data_path, str(i) + ".png")))
# Horizontal axis flip of initial_image
i += 1
y.append(float_im(save_np_img(np.flipud(initial_image), y_data_path, str(i) + ".png")))
else:
continue
return np.array(y)
def save_np_img(np_img, path, name):
"""
To save the image.
:param np_img: numpy_array type image
:param path: string type of the existing path where to save the image
:param name: string type that includes the format (ex:"bob.png")
:return: numpy array
"""
if type(np_img[0][0][0].item()) != int:
np_img = np.multiply(np_img, 255).astype(int)
im = Image.fromarray(np_img)
im.save(path + name)
return np_img
这是我的任务管理器中的示例。查看左下方的Committed
字段:
它一直不断增加直到达到最大值(23.9GB),然后发生以下错误:
...
2184 images processed
2212 images processed
2240 images processed
2268 images processed
2296 images processed
Traceback (most recent call last):
File "main.py", line 11, in <module>
prepare_data.load_imgs(hr_img_path + "*.png") # TODO: customize path (command line)
File "C:\Users\payne\Documents\GitHub\PixelEnhancer\SR-ResCNN-Keras-\prepare_data.py", line 73, in load_imgs
y_train = random_crop(images)
File "C:\Users\payne\Documents\GitHub\PixelEnhancer\SR-ResCNN-Keras-\prepare_data.py", line 62, in random_crop
y.append(float_im(save_np_img(np.flipud(initial_image), y_data_path, str(i) + ".png")))
File "C:\Users\payne\Documents\GitHub\PixelEnhancer\SR-ResCNN-Keras-\utils.py", line 27, in float_im
return np.divide(img, 255.)
MemoryError
我应该如何修改我的代码,以使该错误不再发生? python 3.5如何检测到我已达到内存的最大容量?我正在使用它来预处理图像以训练神经网络。