How to read the RGB value of a given pixel in Python?


If I open an image with open("image.jpg"), how can I get the RGB values of a pixel assuming I have the coordinates of the pixel?

Then, how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?

I would prefer if I didn't have to download any additional libraries.

12/10/2018 10:10:22 AM

Accepted Answer

It's probably best to use the Python Image Library to do this which I'm afraid is a separate download.

The easiest way to do what you want is via the load() method on the Image object which returns a pixel access object which you can manipulate like an array:

from PIL import Image

im ='dead_parrot.jpg') # Can be many different formats.
pix = im.load()
print im.size  # Get the width and hight of the image for iterating over
print pix[x,y]  # Get the RGBA Value of the a pixel of an image
pix[x,y] = value  # Set the RGBA Value of the image (tuple)'alive_parrot.png')  # Save the modified pixels as .png

Alternatively, look at ImageDraw which gives a much richer API for creating images.

5/3/2018 10:03:26 AM

PyPNG - lightweight PNG decoder/encoder

Although the question hints at JPG, I hope my answer will be useful to some people.

Here's how to read and write PNG pixels using PyPNG module:

import png, array

point = (2, 10) # coordinates of pixel to be painted red

reader = png.Reader(filename='image.png')
w, h, pixels, metadata = reader.read_flat()
pixel_byte_width = 4 if metadata['alpha'] else 3
pixel_position = point[0] + point[1] * w
new_pixel_value = (255, 0, 0, 0) if metadata['alpha'] else (255, 0, 0)
  pixel_position * pixel_byte_width :
  (pixel_position + 1) * pixel_byte_width] = array.array('B', new_pixel_value)

output = open('image-with-red-dot.png', 'wb')
writer = png.Writer(w, h, **metadata)
writer.write_array(output, pixels)

PyPNG is a single pure Python module less than 4000 lines long, including tests and comments.

PIL is a more comprehensive imaging library, but it's also significantly heavier.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow