2

i want to change a image(17x15) to 2d array with code:

from PIL import Image
import numpy as np

list = []
im = Image.open('plus1.jpg')
row,col =  im.size
print(row,col)
for i in range (row):
   for j in range (col):
        r, g, b = im.getpixel((i, j))
        list.append([r,g,b]) 
print(list)
print(len(list))
list = np.array(list)
print(list)
list.reshape(17,15)

It change okay to 1D array but when i using reshape to make 2D array with list.reshape(17,15) got the error:

ValueError: total size of new array must be unchanged

The size is 17x15, and change to 1D array have 255 elements, so why the error appear and how to make it run normaly?

10
  • Each item in list is a triplet [r, g, b]. This does not fit a numpy array representation. Commented Oct 1, 2016 at 6:48
  • 2
    what is the output of list.shape (which should be done after list = np.array(list))? Commented Oct 1, 2016 at 6:50
  • @AngusWilliams you mean list.reshape? It reshape the array.@Aguy but i success change to 1D array? Commented Oct 1, 2016 at 7:09
  • No, I mean list.shape. This will output the current shape of the array before you try to reshape it. It will hopefully give us some insight into your bug. Just add the line print(list.shape) beneath the line list = np.array(list) and report the output of the print statement. Commented Oct 1, 2016 at 7:12
  • @AngusWilliams the result of list.shape is (255, 1, 3) 255 row, 1 col and 3 elements in each item? Commented Oct 1, 2016 at 7:18

1 Answer 1

1

Your image is 17x15, so there are 255 pixels. For each pixel, there are three color values (r,g,b). This means that your array list has shape (255,1,3). This means that it contains 755 elements, and an error is raised when you try to reshape it to (17,15), which does not preserve the number of elements. To obtain an array that has the first two dimensions the same as your image (17,15), and a third axis that contains the rgb values, you should write:

np.reshape(list, (17,15,3) )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.