How to Use the PIL getpixel() Method in Python

09/17/2021

Contents

In this article, you will learn how to use the PIL getpixel() method in Python.

PIL getpixel() Method

The PIL (Python Imaging Library) is a powerful library for working with images in Python. The getpixel() method is a method of the Image class in PIL that returns the RGB value of a pixel at a specific location in an image. Here’s how to use the getpixel() method in Python:

Import the PIL library and open the image you want to work with using the Image.open() method:

from PIL import Image

img = Image.open('image.jpg')

Call the getpixel() method on the image object and pass in the x and y coordinates of the pixel you want to retrieve:

pixel = img.getpixel((x, y))

Where x and y are the pixel coordinates in the image. Note that the coordinates start at (0,0) in the top-left corner of the image.

The getpixel() method returns a tuple of the RGB values of the pixel. You can access each value individually using indexing:

r = pixel[0]
g = pixel[1]
b = pixel[2]

Here’s an example of using the getpixel() method to get the RGB value of a pixel at location (100, 200) in an image:

from PIL import Image

img = Image.open('image.jpg')
pixel = img.getpixel((100, 200))

r = pixel[0]
g = pixel[1]
b = pixel[2]

print(f"RGB value at (100, 200): ({r}, {g}, {b})")