我有以下代码使用 opencv 读取图像并显示它:
import cv2, matplotlib.pyplot as plt
img = cv2.imread('imgs_soccer/soccer_10.jpg',cv2.IMREAD_COLOR)
img = cv2.resize(img, (128, 128))
plt.imshow(img)
plt.show()
我想使用 keras 生成一些随机图像,所以我定义了这个生成器:
image_gen = ImageDataGenerator(rotation_range=15,
width_shift_range=0.1,
height_shift_range=0.1,
shear_range=0.01,
zoom_range=[0.9, 1.25],
horizontal_flip=True,
vertical_flip=False,
fill_mode='reflect',
data_format='channels_last',
brightness_range=[0.5, 1.5])
但是,当我以这种方式使用它时:
image_gen.flow(img)
我收到这个错误:
'Input data in `NumpyArrayIterator` should have rank 4. You passed an array with shape', (128, 128, 3))
这对我来说似乎很明显:RGB,图像,当然是 3 维的!我在这里错过了什么?文档说它需要一个 4 维数组,但没有指定我应该在第 4 维中放置什么!
这个 4 维数组应该如何制作?我现在有(宽度、高度、 channel ),这个第 4 个维度是在开始还是结束?
我对 numpy 也不是很熟悉:如何更改现有的 img 数组以添加第 4 维?
使用np.expand_dims()
:
import numpy as np
img = np.expand_dims(img, 0)
print(img.shape) # (1, 128, 128, 3)
第一个维度指定图像的数量(在您的例子中是 1 张图像)。
我是一名优秀的程序员,十分优秀!