Sean
Sean

Reputation: 3

Converting list to numpy array issues

Using python xy's spyder code editor.

When saving a list of pixel color values to a numpy array using np.asarray(list), it gives me an array with weird dimensions.

The dimensions of the original image being read is (864,1089) (width,height) and is a JPEG image. When converting this list to a numpy array, it returns an array with dimensions (940896, 3), when I expected a one dimensional array with dimensions (940896,). I don't understand where the 3 came from...

img = Image.open('Images\satellite6.jpg')
pix = img.load()
width = img.size[0]
height = img.size[1]
pixels = []

for j in range(height):
    for i in range(width):
        pixels.append(pix[i,j])

pixels = np.array(pixels)
print np.shape(pixels)

(940896, 3)

I am also new to posting questions, so if anything seems unclear, let me know :)

Upvotes: 0

Views: 286

Answers (1)

a5kin
a5kin

Reputation: 1425

Try to see what pix[0,0] contains for example:

>>> img = Image.open('./edgewalker-cat.png')
>>> pix = img.load()
>>> pix
<PixelAccess object at 0x7f1afac932f0>
>>> pix[0,0]
(0, 0, 0)

Its tuple, size of 3, so the pixels list, you are constructing one by one item, will be converted to the dimension of (width*height, 3).

UPD: On grayscaled images, you'll get a plain int value:

>>> img = Image.open('./urban-dove-gray.jpg')
>>> pix = img.load()
>>> pix[0,0]
31

Upvotes: 1

Related Questions