Python PIL getpixel() method to get pixel value

Python PIL getpixel() method provides image data at pixel level. You can extract the pixel value by passing it’s (x,y) coordinates.

getpixel() Syntax

Syntax: getpixel(xy)
Parameters: xy, pixel coordinates represented as a tuple (x,y) i.e.(row, column)

Returns: a pixel value for single band images (grey-scale images), a tuple of pixel values for multi-layer images. For RGB image, it returns R,G,B value at the given pixel position.

Examples

Get Pixel Value from image

Used Image
# Importing Image module from PIL package
from PIL import Image

# creating an image object
im = Image.open(r"C:\Users\Desktop\_Archive\blog_ghs\automate-the-boring-stuff-with-python.jpg")

# loading the pixel data of the image
pix = im.load()

# Creating coordinates of the pixel (x,y)
coordinates = x, y = 40, 60

# getting pixel value using getpixel() method
print(im.getpixel(coordinates));

Output:

Extract all pixel values from image

# Importing Image module from PIL package
from PIL import Image

# creating an image object
im = Image.open(r"C:\Users\Desktop\_Archive\blog_ghs\automate-the-boring-stuff-with-python.jpg")

# loading the pixel data of the image
pix = im.load()

# For loop to extract and print all pixels
for x in range(im.width):
    for y in range(im.width):
        # getting pixel value using getpixel() method
        print(im.getpixel((x,y)))

Output:

(250, 245, 189)
(255, 251, 203)
(253, 251, 203)
(255, 253, 202)
(247, 246, 189)
(239, 245, 173)
(243, 250, 182)
(254, 255, 204)
(255, 255, 207)
(250, 245, 187)
(239, 234, 166)
(231, 225, 147)
(250, 246, 173)
(255, 255, 202)
(255, 255, 214)
(255, 254, 209)
(239, 236, 181)
(236, 229, 159)
(250, 246, 175)
.
.
.
.

Notes:

  1. Above codes are validated with Python 3.7 using PyCharm 2019.3.3 on Windows 10 PC

References:

  1. Python PIL Image Module reference

Related:
Python PIL | pil.unidentifiedimageerror: cannot identify image error
How to download Instagram Images using Python?
Python Pillow (PIL) Tutorial [Installation and Examples]

About the Author

SRINI S

A passionate blogger. Love to share solutions and best practices on wordpress hosting, issues and fixes, excel VBA macros and other apps

Leave a Reply

Your email address will not be published.