Introduction
Image processing transforms, analyzes, and manipulates images using Python libraries like PIL and OpenCV.
PIL Basics
from PIL import Image
import numpy as np
# Open image
img = Image.open('photo.jpg')
print(img.size, img.mode) # (width, height), RGB
# Convert mode
img_rgb = img.convert('RGB')
img_gray = img.convert('L')
# Save
img.save('output.png')
# Create new image
new_img = Image.new('RGB', (100, 100), color='red')
OpenCV Basics
import cv2
import numpy as np
# Read image
img = cv2.imread('photo.jpg')
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Write
cv2.imwrite('output.jpg', img)
# Get shape
print(img.shape) # (height, width, channels)
Image Transformations
import cv2
import numpy as np
# Resize
resized = cv2.resize(img, (200, 200))
# Rotate
(h, w) = img.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, 45, 1.0)
rotated = cv2.warpAffine(img, M, (w, h))
# Flip
flipped = cv2.flip(img, 1) # 1=horizontal, 0=vertical
# Crop
cropped = img[50:150, 100:200]
Image Arithmetic
import cv2
import numpy as np
# Add images
added = cv2.add(img1, img2)
# Blend
blended = cv2.addWeighted(img1, 0.7, img2, 0.3, 0)
# Mask
mask = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY)[1]
result = cv2.bitwise_and(img, img, mask=mask)
Color Manipulation
import cv2
import numpy as np
# HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Extract channel
blue = img[:, :, 0]
# Adjust brightness
bright = cv2.convertScaleAbs(img, beta=50)
# Adjust contrast
contrast = cv2.convertScaleAbs(img, alpha=1.5, beta=0)
Practice Problems
- Open and save images
- Resize and rotate
- Crop and flip
- Blend images
- Convert color spaces