【问题标题】:Converting Images to Numpy arrays with correct dimension将图像转换为具有正确尺寸的 Numpy 数组
【发布时间】:2021-01-05 23:04:01
【问题描述】:

我正在尝试将 100 个图像转换为一个 numpy 数组,然后将其输入我的神经网络。 我的 NN 训练数据是 4D numpy 数组(图像数量,32、32、3)。 当使用以下代码读取图像并输入 model.predict() 时,出现以下错误。

“检查输入时出错:预期 conv2d_input 有 4 维,但得到的数组形状为 (100, )”

这是我写的代码:

'''new_data = []
files = glob.glob (r"load images")
for myFile in files:
    #print(myFile)
    image = cv2.imread(myFile)
    new_data.append(np.asarray(image))
    
#new_data = np.array(new_data)
print('new_data shape:', np.array(new_data).shape)'''

输出是“new_data shape: (100,)”

我期望 new_data 维度为 (100, 32, 32, 3)。请帮助了解如何实现这一目标。

谢谢, 米纳尔

【问题讨论】:

  • 你为什么要np.asarray?简单地将其附加到列表中。
  • 用new_data.append(im)试过了,结果还是一样
  • cv2 将图像作为数组读取,而 Pillow 不会。
  • 检查数组中所有图像的shape。它可能不同,产生一个 1d 对象 dtype 数组。

标签: image numpy tensorflow readimage


【解决方案1】:

感谢所有回复。问题是图像大小不同。在我将它们全部调整为 32*32 并执行 np.reshape() 之后。 下面是修改后的代码

files = glob.glob (r"files\*.png*")
for myFile in files:
    image = cv2.imread(myFile)
    img = cv2.resize(image , (32 , 32)) # Reshaping the testing images to 32*32
    new_data.append(img)



new_data = np.reshape(new_data, (len(new_data),32,32,3))   

【讨论】:

    【解决方案2】:

    你可以直接使用 PILLOW 库

    from PIL import Image
    from numpy import asarray
    
    image = Image.open('kolala.jpeg')
    # convert image to numpy array
    data = asarray(image)
    print(type(data))
    
    print(data.shape)
    
    
    image2 = Image.fromarray(data)
    print(type(image2))
    

    【讨论】:

      猜你喜欢
      • 2015-12-12
      • 2021-10-09
      • 2018-05-31
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 2018-11-12
      • 1970-01-01
      相关资源
      最近更新 更多