gpt4 book ai didi

python - 图像数据生成器 : how to add the 4th dimension to a numpy array?

转载 作者:太空宇宙 更新时间:2023-11-03 14:38:11 25 4
gpt4 key购买 nike

我有以下代码使用 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 张图像)。

关于python - 图像数据生成器 : how to add the 4th dimension to a numpy array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55834790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com