ValueError: could not broadcast input array from shape (110,110,3) into shape (110,110)

Viewed 6458

I'm building a neural network and I'm trying to load colored images into the network but I keep getting a reshaping error. I resized all of the images to the smallest dimensions (in this case 110 x 110) but when I try to convert the X (an unflattened 3d list of the pixels of each image) to a numpy array to be called xTrain with this line of code:

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

i get this error: "ValueError: could not broadcast input array from shape (110,110,3) into shape (110,110)"

does anyone know why it keeps doing that? i assume it's because of my data because my partner copied the same exact code with his own images and the conversion to a numpy array was successful but mine isn't. for reference the list titled X is in this format:

[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],...

how do I fix this?

2 Answers

Most likely, your X list contains a mixture of grayscale and RGB images.


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)

You can convert the grayscale image(s) in X to 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

The problem while reshaping arises because python can not convert an array of shape (110,110,3) to (110,110). The 3 in the shape of the array signifies the RGB or BGR colour code (varies between different image reading functions).Also, product of the length of the array about all axes should stay constant. This means that say, your array is of size (x1, y1, z1) and you reshape it to (x2,y2,z2) then x1y1z1 = x2y2z2 or else the reshape function will give an error.

The most simple walk-around is to read the image as a greyscale image. In opencv, it is implemented as below:

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))

Related