Last modified: Apr 12, 2025 By Alexander Williams
Python Get Image Pixels Guide
Working with image pixels is a common task in Python. This guide shows how to read and manipulate image pixels using the Pillow library.
Table Of Contents
Why Get Image Pixels in Python?
Accessing image pixels lets you analyze or modify images. Common uses include image processing, computer vision, and data analysis.
For more on image processing, see our Python Image Processing Guide.
Install Pillow Library
First, install Pillow using pip:
pip install Pillow
Load an Image in Python
Use Image.open()
from Pillow to load an image:
from PIL import Image
# Open an image file
img = Image.open('example.jpg')
Get Image Pixel Data
The load()
method gives access to pixel data:
pixels = img.load()
width, height = img.size
# Get pixel at (x=10, y=20)
pixel_value = pixels[10, 20]
print(pixel_value)
(255, 0, 0) # Red pixel in RGB format
Modify Image Pixels
You can change pixel values directly:
# Change pixel at (10, 20) to green
pixels[10, 20] = (0, 255, 0)
# Save modified image
img.save('modified.jpg')
Get All Pixels in an Image
Loop through all pixels to process the entire image:
for x in range(width):
for y in range(height):
r, g, b = pixels[x, y]
# Process each pixel here
Convert Image to NumPy Array
For advanced processing, convert to a NumPy array:
import numpy as np
img_array = np.array(img)
print(img_array.shape) # (height, width, channels)
For more image libraries, check our Python Image Libraries Guide.
Common Pixel Operations
Here are some common pixel operations:
# Grayscale conversion
gray_pixel = sum(pixels[x, y]) // 3
# Invert colors
inverted = tuple(255 - val for val in pixels[x, y])
Performance Considerations
Important: Pixel access can be slow for large images. For better performance:
1. Use NumPy arrays for bulk operations
2. Process smaller image sections
3. Consider parallel processing
Saving Modified Images
After modifying pixels, save the image:
img.save('output.png', format='PNG')
For saving options, see our Python Pygame Image Save Guide.
Conclusion
Getting image pixels in Python is easy with Pillow. You can read, modify, and save pixel data for various applications.
Remember to handle large images carefully for best performance. The techniques shown work for most image processing tasks.