Search code examples
pythonnumpyimage-processingpython-imaging-library

numpy.resize throws valueError despite image matrix product equaling the total image size


I am trying to resize a grayscale image into a numpy array like so:

return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)

and getting this error:

ValueError: cannot reshape array of size 1909760 into shape (1024,1865,3)

I've read that the product of an images columns and rows (1024 x 1865) is supposed to equal the size of the array being reshaped - (1909760) which it does. I've also tried the same code on images with three channels and it works.


Solution

  • If you're using the PIL module for your image, you could try converting it to an RGB before getting the data. Something like this should work:

    image = image.convert("RGB")
    return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)
    

    This works because when you convert from a grayscale to an RGB, PIL automatically sets each pixel to have three values, an R, G, and B.