Reputation: 93
I have a question about the Python module PIL:
Whenever I call the getdata()
method on an image, I get something weird returned.
from PIL import Image
# Histogram class to get the data
class Histogram:
def __init__(self, image):
image.convert("RGB")
pixel_value_list = list(image.getdata())
print(pixel_value_list[1])
image = Image.open("lenna.gif")
histogram = Histogram(image)
But I do not get a tuple printed to the console, but somehow 45...
Why does the list(image.getdata())
not return a list with tuples but a list entirely made of integers?
Upvotes: 5
Views: 12755
Reputation: 1619
If you open a palettized file (like a GIF), and print the list of pixels via .getdata()
, you'll get a list of indexes into the palette, e.g.:
im = Image.open("composplot.gif")
print(list(im.getdata()))
Output:
[0, 0, 0, 0, 0, 0, 0, 0, 6, 223, 0, 0, 46, 219, 195, ...]
However, if your convert the palettized image to a RGB image, you'll get a list of (r,g,b) tuples. Example:
im = Image.open("composplot.gif")
imrgb = im.convert("RGB")
print(list(imrgb.getdata()))
Output:
[(255, 255, 255), (255, 255, 255), (216, 216, 216), (8, 8, 8), (191, 191, 191), (255, 255, 255), ...]
Upvotes: 4