Last modified: Apr 12, 2025 By Alexander Williams
Python Image Processing Guide
Python is a powerful language for image processing. It offers many libraries to work with images. This guide covers the basics.
Why Use Python for Image Processing?
Python is easy to learn. It has many libraries for image tasks. You can automate editing, analysis, and more.
Popular libraries include Pillow and OpenCV. They help with resizing, filtering, and object detection. Check our Python Image Libraries Guide for more.
Getting Started with Pillow
Pillow is a fork of PIL (Python Imaging Library). It's great for basic image operations. First, install it:
# Install Pillow
pip install pillow
Now let's open and display an image:
from PIL import Image
# Open an image
img = Image.open('example.jpg')
# Show the image
img.show()
Basic Image Operations
Pillow makes basic edits simple. You can resize, rotate, and crop images. Here's how:
# Resize image
resized_img = img.resize((300, 200))
# Rotate image
rotated_img = img.rotate(45)
# Crop image
box = (100, 100, 400, 400)
cropped_img = img.crop(box)
For advanced compression, see our Image Compression Guide.
Working with OpenCV
OpenCV is better for complex tasks. It supports face detection and more. Install it with:
# Install OpenCV
pip install opencv-python
Here's how to read and display an image:
import cv2
# Read image
img = cv2.imread('example.jpg')
# Display image
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Image Filtering
Filters enhance or modify images. Common ones include blur and edge detection. Here's an example:
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Apply Gaussian blur
blur = cv2.GaussianBlur(gray, (5,5), 0)
# Detect edges
edges = cv2.Canny(blur, 100, 200)
Saving Images
After editing, save your work. Both libraries make it easy:
# Save with Pillow
img.save('new_image.jpg')
# Save with OpenCV
cv2.imwrite('new_image.jpg', img)
For Pygame specific saves, see our Pygame Image Save Guide.
Conclusion
Python makes image processing accessible. Pillow is great for basic edits. OpenCV handles advanced computer vision.
Start with simple tasks. Gradually try complex operations. The possibilities are endless.