Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading PNG with PIL in Python

I am reading a PNG file in Python. I want the RGB values for each pixel in the image:

  img = Image.open(path)
  pixels = img.load()

For a JPEG file the pixels are a tuple but for PNGs I am getting a single integer. How should I read PNG images with Python to get the pixel values?

like image 600
dulla Avatar asked Nov 09 '15 21:11

dulla


People also ask

Does PIL support png?

PIL is a free library that adds image processing capabilities to your Python interpreter, supporting a range of image file formats such as PPM, PNG, JPEG, GIF, TIFF and BMP.

How do I open an image with PIL?

Image. open() Opens and identifies the given image file. This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the load() method).


1 Answers

Sounds like the image is being opened in grayscale mode. Try converting to RGB before accessing the pixel values.

img = Image.open(path).convert("RGB")
pixels = img.load()
like image 142
Kevin Avatar answered Sep 18 '22 17:09

Kevin