Image Processing
3. Image Processing & Optimization
This section covers how to modify images, change file extensions, resize graphics, and analyze pixels using code.
Tools & Libraries
- Pillow (PIL Fork): The standard Python library used to open, edit, resize, and save graphic images. It is "friendly" and easy to use for common tasks.
- OpenCV (
opencv-python): A high-performance computer vision library used for advanced matrix math, object detection, and real-time video processing.
Core Methods & Code Example
1. Format Conversion (Pillow)
Image.open('input.jpg') & Image.save('output.png')
How it works: Opens a picture file into memory and writes it back out to the disk, handling format conversions automatically.
2. Proportional Resizing (Pillow)
Image.thumbnail((max_w, max_h))
How it works: Resizes a picture to fit within specific width/height limits while maintaining the aspect ratio (so it doesn't look "stretched").
3. Matrix-Based Processing (OpenCV)
cv2.imread() & cv2.imwrite()
How it works: Opens images as NumPy matrices (grids of numbers). This allows for deep mathematical manipulation of pixels, such as color-space shifting.
from PIL import Image
import cv2
# --- Pillow Example: Quick Resizing & Conversion ---
# Opens 'profile.jpg', shrinks it to fit 400x400, and converts to PNG
with Image.open('profile.jpg') as img:
img.thumbnail((400, 400))
img.save('profile_optimized.png', 'PNG')
# --- OpenCV Example: Advanced Pixel Manipulation ---
# Load the image as a mathematical matrix (BGR format by default)
matrix_image = cv2.imread('profile_optimized.png')
# Apply a color transformation: Convert BGR color grid to Grayscale
grayscale_image = cv2.cvtColor(matrix_image, cv2.COLOR_BGR2GRAY)
# Save the final result
cv2.imwrite('profile_gray.png', grayscale_image)