OpenCV Python Interactive Guide

OpenCV Python Interactive Guide | OpenCV Python 互動指南

OpenCV in Python: Interactive Learning Guide

Master computer vision with hands-on examples and real-time visualization

📊 Learning Progress

Completed Lessons 0 / 5

📚 Interactive Lessons

💡 Quick Start

OpenCV can be installed in minutes using Python's package manager.

Step 1: Install OpenCV

# Install basic OpenCV pip install opencv-python # Install with contrib modules (optional) pip install opencv-contrib-python

Step 2: Verify Installation

import cv2 print(cv2.__version__) # Should print version like '4.5.3'
✅ Prerequisites
  • Python 3.6 or higher installed
  • pip package manager available
  • Internet connection for downloading

Reading and Displaying Images

import cv2 # Read image from file img = cv2.imread('image.jpg') # Display image in window cv2.imshow('My Image', img) cv2.waitKey(0) # Wait for key press cv2.destroyAllWindows() # Close windows
🔍 Understanding BGR Format

OpenCV uses BGR (Blue-Green-Red) instead of RGB for historical reasons. Each pixel is a 3D array [B, G, R].

Try It: Load Your Own Image

Original Image (BGR)

Image Transformations

Grayscale Conversion
Convert color image to grayscale using weighted average: 0.299*R + 0.587*G + 0.114*B
Resizing
Change image dimensions while maintaining aspect ratio
Thresholding
Convert to binary image: pixels above threshold → white, below → black
# Grayscale conversion gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Resize image resized = cv2.resize(img, (width, height)) # Thresholding _, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

Interactive Controls

Threshold Value 127
Blur Kernel Size 5
Grayscale
Threshold Binary
Gaussian Blur

Canny Edge Detection

🎯 How Canny Works
  1. Apply Gaussian blur to reduce noise
  2. Calculate intensity gradients
  3. Non-maximum suppression to thin edges
  4. Double thresholding to detect strong edges
  5. Edge tracking by hysteresis
# Canny edge detection pipeline import cv2 # 1. Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 2. Apply Gaussian blur blurred = cv2.GaussianBlur(gray, (5, 5), 0) # 3. Apply Canny edge detection edges = cv2.Canny(blurred, 50, 150) # Parameters: low_threshold=50, high_threshold=150

Experiment with Parameters

Low Threshold 50
High Threshold 150
Original Image
Canny Edge Detection
💡 Tuning Tips
  • Lower thresholds detect more edges (including weak ones)
  • Higher thresholds only detect strong edges
  • Typical ratio: high_threshold = 2-3 × low_threshold

Face Detection with Haar Cascades

👤 About Haar Cascades

Haar Cascade is a machine learning object detection method using pre-trained classifiers. OpenCV provides built-in cascades for faces, eyes, and more.

import cv2 # Load pre-trained face detector face_cascade = cv2.CascadeClassifier( cv2.data.haarcascades + 'haarcascade_frontalface_default.xml' ) # Read image and convert to grayscale img = cv2.imread('photo.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Detect faces faces = face_cascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=4 ) # Draw rectangles around faces for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)

Detection Parameters

Scale Factor 1.1
Min Neighbors 4
Face Detection Result (Simulated)
scaleFactor
How much image size is reduced at each scale. Smaller = more accurate but slower.
minNeighbors
How many neighbors each rectangle should have to retain it. Higher = fewer false positives.
🎓 Real-World Applications
  • Security systems and surveillance
  • Photo tagging and organization
  • Augmented reality filters
  • Attendance tracking systems

🔖 Quick Reference

cv2.imread()
Load image from file into NumPy array
cv2.cvtColor()
Convert between color spaces (BGR, RGB, Gray)
cv2.resize()
Change image dimensions
cv2.threshold()
Apply thresholding to binarize image
cv2.GaussianBlur()
Smooth image using Gaussian kernel
cv2.Canny()
Detect edges in image

🚀 Next Steps

Continue Your Learning Journey
  • Practice with different images to understand variations
  • Explore video processing with cv2.VideoCapture()
  • Learn about contour detection and shape analysis
  • Study deep learning integration with OpenCV DNN module
  • Build practical projects: QR code scanner, motion detector, etc.

留言

此網誌的熱門文章

Ember's Whisper: A Journey of Fiery Hearts