OpenCV Python Guide
Table of Contents
- Image Operations
- Reading Images
- Blurring Images
- Saving Images
- Cropping Images
- Displaying Images
- Video Operations
- Reading Video Files
- Processing Video Frames
- Complete Examples
Image Operations
Reading Images
import cv2
# Read an image from file
image = cv2.imread("image.jpg")
# Returns: numpy array (BGR format)
# Returns None if file doesn't exist
# Read with specific flags
image_gray = cv2.imread("image.jpg", cv2.IMREAD_GRAYSCALE)
image_unchanged = cv2.imread("image.jpg", cv2.IMREAD_UNCHANGED)
Parameters:
- filename (str): Path to the image file
- flags (optional): How to read the image
- cv2.IMREAD_COLOR - Load color image (default)
- cv2.IMREAD_GRAYSCALE - Load as grayscale
- cv2.IMREAD_UNCHANGED - Load with alpha channel
Blurring Images
# Simple blur (averaging)
blurred = cv2.blur(image, (50, 50))
Parameters:
- src: Source image
- ksize: Kernel size as tuple (width, height)
- Larger values = more blur
- Both values must be positive and odd numbers work best
Other blur methods:
# Gaussian blur (more natural, handles edges better)
gaussian_blur = cv2.GaussianBlur(image, (51, 51), 0)
# Median blur (good for salt-and-pepper noise)
median_blur = cv2.medianBlur(image, 51)
# Bilateral filter (preserves edges while blurring)
bilateral = cv2.bilateralFilter(image, 9, 75, 75)
Saving Images
# Save image to file
cv2.imwrite("output.png", blurred)
Parameters:
- filename (str): Output file path with extension
- img: Image array to save
Supported formats:
- .jpg / .jpeg - JPEG format
- .png - PNG format (supports transparency)
- .bmp - Bitmap format
- .tiff - TIFF format
Example with quality settings:
# Save JPEG with quality (0-100, default 95)
cv2.imwrite("output.jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 90])
# Save PNG with compression (0-9, default 3)
cv2.imwrite("output.png", image, [cv2.IMWRITE_PNG_COMPRESSION, 5])
Cropping Images
Important: OpenCV doesn't have a dedicated crop function. Use NumPy array slicing instead.
# Crop using array slicing
# Syntax: image[y1:y2, x1:x2]
# Note: y comes first, then x (row, column)
cropped = image[240:450, 680:900]
Understanding the syntax:
image[start_row:end_row, start_col:end_col]
image[y1:y2, x1:x2]
Visual representation:
x1=680 x2=900
y1=240 ├──────────┐
│ Cropped │
│ Area │
y2=450 └──────────┘
Examples:
# Crop center 200x200 region
height, width = image.shape[:2]
center_x, center_y = width // 2, height // 2
cropped_center = image[
center_y - 100:center_y + 100,
center_x - 100:center_x + 100
]
# Crop top-left quarter
cropped_quarter = image[0:height//2, 0:width//2]
# Crop bottom-right corner (200x200)
cropped_corner = image[-200:, -200:]
Displaying Images
# Display image in a window
cv2.imshow("Window Title", image)
# Wait for key press (required to keep window open)
cv2.waitKey(0) # 0 = wait indefinitely
# Close all windows
cv2.destroyAllWindows()
Parameters:
- winname (str): Window name/title
- mat: Image to display
waitKey() usage:
# Wait indefinitely until any key is pressed
cv2.waitKey(0)
# Wait 1000ms (1 second), then continue
cv2.waitKey(1000)
# Wait 1ms (used in video loops)
cv2.waitKey(1)
# Check for specific key press
key = cv2.waitKey(0)
if key == ord('q'): # Press 'q' to quit
print("Q key pressed")
elif key == 27: # ESC key
print("Escape pressed")
Video Operations
Reading Video Files
# Create VideoCapture object
video_capture = cv2.VideoCapture("video.mov")
# Check if video opened successfully
if not video_capture.isOpened():
print("Error: Could not open video file")
exit()
# Get video properties
fps = video_capture.get(cv2.CAP_PROP_FPS)
width = int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
frame_count = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
print(f"FPS: {fps}, Size: {width}x{height}, Frames: {frame_count}")
Video sources:
# From file
cap = cv2.VideoCapture("video.mp4")
# From webcam (0 = default camera)
cap = cv2.VideoCapture(0)
# From IP camera
cap = cv2.VideoCapture("rtsp://camera_ip:port/stream")
Processing Video Frames
# Process video frame by frame
video_capture = cv2.VideoCapture("video.mov")
while video_capture.isOpened():
# Read frame
success, frame = video_capture.read()
# success: True if frame read successfully, False otherwise
# frame: The actual frame (numpy array)
if success:
# Process frame (example: convert to grayscale)
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display frame
cv2.imshow("Video", frame)
# Wait 25ms between frames (40 FPS)
# Break loop if 'q' is pressed
if cv2.waitKey(25) & 0xFF == ord('q'):
break
else:
# End of video or error
break
# Release resources
video_capture.release()
cv2.destroyAllWindows()
Understanding waitKey() in video loops:
# 0xFF is a bitmask to get last 8 bits
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Equivalent simpler version (works in most cases)
if cv2.waitKey(1) == ord('q'):
break
Complete Examples
Example 1: Basic Image Processing Pipeline
import cv2
# Read image
image = cv2.imread("input.jpg")
if image is None:
print("Error: Could not read image")
exit()
# Get image dimensions
height, width = image.shape[:2]
print(f"Image size: {width}x{height}")
# Apply blur
blurred = cv2.blur(image, (50, 50))
# Crop center region
crop_size = 200
center_x, center_y = width // 2, height // 2
cropped = image[
center_y - crop_size:center_y + crop_size,
center_x - crop_size:center_x + crop_size
]
# Save results
cv2.imwrite("output_blurred.png", blurred)
cv2.imwrite("output_cropped.png", cropped)
# Display images
cv2.imshow("Original", image)
cv2.imshow("Blurred", blurred)
cv2.imshow("Cropped", cropped)
print("Press any key to close windows...")
cv2.waitKey(0)
cv2.destroyAllWindows()
Example 2: Video Processing with Frame Saving
import cv2
import os
# Create output directory
os.makedirs("frames", exist_ok=True)
# Open video file
video_capture = cv2.VideoCapture("video.mov")
if not video_capture.isOpened():
print("Error: Cannot open video")
exit()
frame_count = 0
while video_capture.isOpened():
success, frame = video_capture.read()
if success:
# Apply processing (example: blur)
processed = cv2.GaussianBlur(frame, (15, 15), 0)
# Display frame
cv2.imshow("Video", processed)
# Save every 30th frame
if frame_count % 30 == 0:
cv2.imwrite(f"frames/frame_{frame_count:04d}.jpg", processed)
print(f"Saved frame {frame_count}")
frame_count += 1
# Exit on 'q' press or ESC
key = cv2.waitKey(25) & 0xFF
if key == ord('q') or key == 27:
print("User stopped playback")
break
else:
print("End of video or read error")
break
# Clean up
video_capture.release()
cv2.destroyAllWindows()
print(f"Total frames processed: {frame_count}")
Example 3: Webcam with Real-time Processing
import cv2
# Open default webcam
cap = cv2.VideoCapture(0)
# Set resolution (optional)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
print("Press 'q' to quit, 's' to save snapshot")
while True:
ret, frame = cap.read()
if not ret:
print("Failed to grab frame")
break
# Flip frame horizontally (mirror effect)
frame = cv2.flip(frame, 1)
# Add text overlay
cv2.putText(
frame,
"Press 'q' to quit, 's' to save",
(10, 30),
cv2.FONT_HERSHEY_SIMPLEX,
0.7,
(0, 255, 0),
2
)
# Display frame
cv2.imshow("Webcam", frame)
# Handle key presses
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
elif key == ord('s'):
cv2.imwrite("snapshot.jpg", frame)
print("Snapshot saved!")
# Release resources
cap.release()
cv2.destroyAllWindows()
Common Mistakes & Fixes
❌ Wrong: VideoCapture (capital C)
videocapture = cv2.videoCapture("video.mov") # Wrong!
✅ Correct: VideoCapture
video_capture = cv2.VideoCapture("video.mov") # Correct
❌ Wrong: waitkey (lowercase k)
cv2.waitkey(0) # Wrong!
✅ Correct: waitKey
cv2.waitKey(0) # Correct
❌ Wrong: Cropping with x, y order
cropped = image[x1:x2, y1:y2] # Wrong! x and y reversed
✅ Correct: Cropping with y, x order
cropped = image[y1:y2, x1:x2] # Correct - rows (y) first, then columns (x)
Quick Reference
Essential Functions
| Function | Purpose | Example |
|---|---|---|
cv2.imread() |
Read image | img = cv2.imread("file.jpg") |
cv2.imwrite() |
Save image | cv2.imwrite("out.png", img) |
cv2.imshow() |
Display image | cv2.imshow("Title", img) |
cv2.waitKey() |
Wait for key | cv2.waitKey(0) |
cv2.VideoCapture() |
Open video | cap = cv2.VideoCapture("vid.mp4") |
cv2.destroyAllWindows() |
Close windows | cv2.destroyAllWindows() |
Common Key Codes
| Key | Code | Usage |
|---|---|---|
| 'q' | ord('q') |
if key == ord('q') |
| ESC | 27 |
if key == 27 |
| Space | 32 |
if key == 32 |
| Enter | 13 |
if key == 13 |
Tips & Best Practices
-
Always check if image/video loaded:
python if image is None: print("Error loading image") -
Release resources after use:
python video_capture.release() cv2.destroyAllWindows() -
Use appropriate blur kernel sizes:
- Kernel values should be positive and odd
- Larger values = more blur
-
Start small (3, 5, 7) and increase
-
Remember array indexing:
- Images are NumPy arrays:
[rows, columns]=[y, x] - Height = number of rows
-
Width = number of columns
-
Handle exceptions:
python try: image = cv2.imread("file.jpg") if image is None: raise ValueError("Could not load image") except Exception as e: print(f"Error: {e}")
Additional Resources
- Official Documentation: https://docs.opencv.org/
- OpenCV Python Tutorials: https://docs.opencv.org/master/d6/d00/tutorial_py_root.html
- Image coordinate system: (0,0) is top-left corner
Happy coding with OpenCV! 🎥📸