【问题标题】:ValueError: could not broadcast input array from shape (110,110,3) into shape (110,110)ValueError:无法将输入数组从形状(110,110,3)广播到形状(110,110)
【发布时间】:2020-10-18 23:05:32
【问题描述】:

我正在构建一个神经网络,并尝试将彩色图像加载到网络中,但我不断收到重塑错误。我将所有图像的大小调整为最小尺寸(在本例中为 110 x 110),但是当我尝试将 X(每个图像的像素的未展平 3d 列表)转换为一个名为 xTrain 的 numpy 数组时,这行代码:

xTrain = np.array(X[:trainNum])

我收到此错误:“ValueError:无法将输入数组从形状 (110,110,3) 广播到形状 (110,110)”

有人知道它为什么一直这样吗?我认为这是因为我的数据,因为我的伙伴用他自己的图像复制了相同的确切代码,并且转换为 numpy 数组是成功的,但我的不是。作为参考,标题为 X 的列表采用以下格式:

[array([[[137, 151, 199],
    [ 93, 114, 166],
    [116, 121, 164],
    ...,
    [124, 124, 175],
    [160, 162, 193],
    [154, 157, 177]],

   [[ 81,  94, 153],
    [106, 123, 184],
    [119, 124, 180],...

我该如何解决这个问题?

【问题讨论】:

    标签: python numpy tensorflow


    【解决方案1】:

    您的 X 列表很可能包含灰度和 RGB 图像的混合。

    
    img_rgb = np.zeros((110, 110, 3))
    img_gry = np.zeros((110, 110))
    
    X_good = [img_rgb, img_rgb, img_rgb]
    np.array(X_good[:])
    # OK
    
    X_bad = [img_rgb, img_gry, img_rgb]
    np.array(X_bad[:])
    # ValueError: could not broadcast input array from shape (110,110,3) into shape (110,110)
    

    您可以将X中的灰度图像转换为RGB:

    def make_rgb(img):
        if len(img.shape) == 3:
            return img
        img3 = np.empty(img.shape + (3,))
        img3[:, :, :] = img[:, :, np.newaxis]
        return img3
    
    X_repaired = [make_rgb(im) for im in X_bad]
    
    np.array(X_repaired[:])
    # No problem
    

    【讨论】:

      【解决方案2】:

      reshape 时出现问题是因为 python 无法将形状为 (110,110,3) 的数组转换为 (110,110)。数组形状中的 3 表示 RGB 或 BGR 颜色代码(因不同的图像读取功能而异)。此外,数组围绕所有轴的长度的乘积应保持不变。这意味着您的数组大小为 (x1, y1, z1) 并且您将其重塑为 (x2,y2,z2) 然后 x1y1z1 = x2y2 z2 否则reshape函数会报错。

      最简单的方法是将图像读取为灰度图像。在opencv中,实现如下:

      import cv2 
        
      # Using cv2.imread() method 
      # Using 0 to read image in grayscale mode 
      img = cv2.imread(path, 0) 
        
      # Displaying the image 
      cv2.imshow('image', img) 
      
      #if your input image is not 110*110, you resize it
      img = cv2.resize(img, (110,110))
      
      

      【讨论】:

      • 是否有不需要灰度化图像的解决方法?
      • 您能否分享您的神经网络架构,以便我了解您要实现的内容?
      猜你喜欢
      • 2018-06-30
      • 2018-06-08
      • 2020-01-21
      • 2018-09-25
      • 2018-04-21
      • 2020-10-09
      • 2021-03-30
      • 2021-08-24
      • 2019-11-28
      相关资源
      最近更新 更多