Ricky
Ricky

Reputation: 113

Wrong number of elements in a numpy array of a PIL-opened image

Below is a simple section of code used to access an image using PIL, convert to a numpy array and then print the number of elements in the array.

The image in question is here - image - and consists of exactly 100 pixels (10x10). However, the numpy array contains 300 elements (where I would expect 100 elements). What am I doing wrong?

import numpy as np
import PIL

impath = 'C:/Users/Ricky/Desktop/testim.tif'
im = PIL.Image.open(impath)
arr = np.array(im)
print arr.size #300

Upvotes: 0

Views: 319

Answers (1)

Giuseppe Cammarota
Giuseppe Cammarota

Reputation: 84

Every image can be composed by 3 bands (Red-Green-Blue or RGB composition). Since your image is a black/white image those three bands are the same. You can see the difference using a colored image.

Try this to see what I mean:

import matplotlib.pyplot as pyplot
# this line above import a matplotlib library for plotting image

import numpy as np
import PIL
impath = 'C:/Users/Ricky/Desktop/testim.tif'
im = PIL.Image.open(impath)
arr = np.array(im)

print arr.shape # (10, 10, 3)
print arr[:, : ,0].size # 100

# next lines actually show the image
pyplot.imshow(arr[:, : ,0], cmap='gray')
pyplot.show()

Upvotes: 1

Related Questions