Home > Software engineering >  ValueError: cannot reshape array of size 30000 into shape (100,100)
ValueError: cannot reshape array of size 30000 into shape (100,100)

Time:07-03

I want to convert PIL to numpy but I get this error what should I do?

    import numpy as np
from PIL import Image
import PIL
import matplotlib.pyplot as plt 
img_path = "F:\Pictures\Reza's WLP\wallpaper\sample.png"
img = Image.open(img_path)
img_2 = img.resize((100,100))
img_array = np.array(img_2.getdata()).reshape(img_2.size[0], img_2.size[1])
plt.imshow(img_array)

ValueError: cannot reshape array of size 30000 into shape (100,100)

CodePudding user response:

Notice that the array is three times bigger than you're expecting (30000 = 3 * 100 * 100). That's because an array representing an RGB image isn't just two-dimensional: it has a third dimension, of size 3 (for the red, green and blue components of the colour).

So:

img_array = np.array(img_2.getdata()).reshape(img_2.size[0], img_2.size[1], 3)

Alternatively, you could specify the third dimension's size as -1. This means you're asking numpy to figure it out from the dimensions you've already told it: it knows that the source has 30000 elements, so if you want to reshape it into (100, 100, x), then x must be 3.

img_array = np.array(img_2.getdata()).reshape(img_2.size[0], img_2.size[1], -1)

CodePudding user response:

try adding a -1 at the end of the reshape like .reshape(a,b,-1)

  • Related