How to Get Pixel Value at a Position in an Image Using Python Pillow?


Pillow - Get pixel value at a position in image

We can get the pixel value in an image at specified coordinates in Pillow, by calling Image.getpixel() function on the given image and passing the pixel coordinates tuple as argument.

Syntax of getpixel() function

The syntax of getpixel() function from PIL.Image module is

PIL.Image.getpixel(xy)

where

ParameterDescription
xyThe coordinate, given as (x, y).

Returns

The function returns the pixel value. Based on the number of channels present in the image, the function can return a tuple where each value in tuple represents the value corresponding to the respective channel.

Examples

1. Get pixel at (50, 100) to while color, in image

In the following example, we read an image test_image.jpg with JPEG format into an Image object. Then, we get the pixel value at the location (50, 100) using Image.getpixel() function.

Python Program

from PIL import Image

# Open the image
image = Image.open("test_image.jpg")

# (x, y) position
xy = (50, 100)

# Get pixel value
pixel_value = image.getpixel(xy)
print(pixel_value)

Output

(85, 72, 55)

Original Image [test_image.jpg]

Python Pillow - Convert image from JPEG to PNG Example - Output image

Summary

In this Python Pillow Tutorial, we learned how to get the pixel value at an XY position in the image using PIL.Image.getpixel() function, with the help of examples.