A comprehensive Python project demonstrating various OpenCV (Open Source Computer Vision Library) capabilities, from basic image operations to real-time face detection.
- Overview
- Features
- Project Structure
- Prerequisites
- Installation
- Usage
- Modules & Sections
- Troubleshooting
- Resources
- License
This project provides hands-on examples of OpenCV functionality in Python, covering:
- Basic image processing (read, display, resize, crop, rotate, flip)
- Drawing shapes and adding text overlays
- Real-time webcam capture and processing
- Image filtering and blurring techniques
- Edge detection and thresholding
- Contour detection and shape recognition
- Real-time face, eye, and smile detection using Haar Cascades
Perfect for beginners learning computer vision and intermediate developers looking for reference implementations.
- β Read and write images from disk
- β Convert between color spaces (BGR β Grayscale)
- β Resize, crop, rotate, and flip images
- β Interactive image processing with user input
- β Draw lines, rectangles, and circles
- β Add custom text with various fonts and colors
- β Overlay graphics on images
- β Gaussian and Median blur filters
- β Custom kernel-based image sharpening
- β Canny edge detection
- β Binary thresholding with Otsu's method
- β Bitwise operations (AND, OR, XOR, NOT)
- β Contour detection and visualization
- β Automated shape classification (Triangle, Square, Circle, etc.)
- β Real-time face detection using Haar Cascades
- β Eye and smile detection within detected faces
- β Region of Interest (ROI) based processing
D:\Desktop\OpenCV\
β
βββ opencv.py # Main tutorial script (11 sections)
βββ face_detection.py # Standalone face detection demo
βββ face_eye_smile.py # Face, eye, and smile detection
β
βββ requirements.txt # Python dependencies
βββ README.MD # This file
β
βββ haarcascade_frontalcatface.xml # Haar Cascade for cat face detection
βββ haarcascade_eye.xml # Haar Cascade for eye detection
βββ haarcascade_smile.xml # Haar Cascade for smile detection
βββ eye.xml # Additional eye detection cascade
β
βββ venv/ # Virtual environment (Python packages)
- Python: 3.7 or higher
- Operating System: Windows, macOS, or Linux
- Webcam: Required for real-time detection features (optional for image processing)
- Image Files: Sample images (e.g.,
Arnab.jpg,monalisha.png,OIP.jpg) for testing
cd D:\Desktop\OpenCVWindows (PowerShell):
python -m venv venv
.\venv\Scripts\Activate.ps1macOS/Linux:
python3 -m venv venv
source venv/bin/activateNote: If PowerShell blocks script execution, run:
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
pip install --upgrade pip
pip install -r requirements.txtThis will install:
opencv-python- OpenCV library for Pythonnumpy- Numerical computing library (required by OpenCV)
python -c "import cv2; print('OpenCV version:', cv2.__version__)"Expected output: OpenCV version: 4.x.x
The opencv.py file contains 11 comprehensive sections. Run it with:
python opencv.pyInteractive Sections:
- Some sections prompt for user input (e.g., image paths, actions)
- Webcam sections require pressing
qto quit - Each image display waits for any key press to continue
Basic Face Detection:
python face_detection.pyFace, Eye & Smile Detection:
python face_eye_smile.pyControls:
- Press
qto quit the webcam window - Ensure your webcam is not being used by another application
| Section | Description | Key Functions |
|---|---|---|
| 1. Basic Image Operations | Read, display, convert to grayscale, resize, save | cv2.imread(), cv2.cvtColor(), cv2.resize(), cv2.imwrite() |
| 2. Interactive Processing | User-driven image operations | Input handling, conditional processing |
| 3. Image Transformations | Resize, crop, rotate, flip operations | cv2.warpAffine(), cv2.flip(), cv2.getRotationMatrix2D() |
| 4. Drawing Shapes & Text | Lines, rectangles, circles, text overlays | cv2.line(), cv2.rectangle(), cv2.circle(), cv2.putText() |
| 5. Webcam Capture | Real-time video feed from camera | cv2.VideoCapture(), frame reading loop |
| 6. Image Filtering | Gaussian blur, median blur, sharpening | cv2.GaussianBlur(), cv2.medianBlur(), cv2.filter2D() |
| 7. Edge Detection | Canny algorithm, binary thresholding | cv2.Canny(), cv2.threshold() |
| 8. Bitwise Operations | Logical operations on images | cv2.bitwise_and(), cv2.bitwise_or(), cv2.bitwise_xor(), cv2.bitwise_not() |
| 9. Contour Detection | Finding and drawing object contours | cv2.findContours(), cv2.drawContours() |
| 10. Shape Detection | Automated shape classification | cv2.approxPolyDP(), cv2.contourArea(), cv2.minEnclosingCircle() |
| 11. Face/Eye/Smile Detection | Real-time detection with Haar Cascades | cv2.CascadeClassifier(), detectMultiScale() |
Simple webcam-based face detection using Haar Cascades. Features:
- Loads cascade classifier
- Captures webcam feed
- Detects faces in real-time
- Draws rectangles around detected faces
Enhanced detection including:
- Face detection
- Eye detection within face regions (ROI)
- Smile detection within face regions
- Text labels for detected features
Solution:
# Activate virtual environment first
.\venv\Scripts\Activate.ps1 # Windows
source venv/bin/activate # macOS/Linux
# Install OpenCV
pip install opencv-pythonCauses & Solutions:
- Camera in use: Close other applications using the webcam (Zoom, Teams, etc.)
- Permission denied: Grant camera permissions in system settings
- Wrong camera index: Try changing
cv2.VideoCapture(0)tocv2.VideoCapture(1)orcv2.VideoCapture(2)
Solution:
# Verify file exists
import os
print(os.path.exists(r"D:\Desktop\OpenCV\haarcascade_frontalcatface.xml"))
# Use absolute paths with raw strings
cascade = cv2.CascadeClassifier(r"D:\Desktop\OpenCV\haarcascade_frontalcatface.xml")Solution:
- Check file path is correct (use raw strings:
r"D:\path\to\image.jpg") - Verify image file exists in the specified location
- Ensure image format is supported (JPG, PNG, BMP, TIFF)
Cause: Trying to process an empty/invalid image
Solution:
# Always check if image loaded successfully
image = cv2.imread("image.jpg")
if image is None:
print("Failed to load image")
else:
# Process image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)Solution:
# Always include waitKey and destroyAllWindows
cv2.imshow("Window", image)
cv2.waitKey(0) # Wait for key press
cv2.destroyAllWindows() # Clean up- Official Docs: https://docs.opencv.org/
- Python Tutorials: https://docs.opencv.org/4.x/d6/d00/tutorial_py_root.html
- API Reference: https://docs.opencv.org/4.x/d6/d00/tutorial_py_root.html
- Pre-trained Cascades: https://github.com/opencv/opencv/tree/master/data/haarcascades
- Common cascades:
haarcascade_frontalface_default.xml- Human face detectionhaarcascade_eye.xml- Eye detectionhaarcascade_smile.xml- Smile detection
- OpenCV Course: https://opencv.org/courses/
- PyImageSearch: https://pyimagesearch.com/
- Real Python - OpenCV: https://realpython.com/opencv-python/
- Stack Overflow: Tag
[opencv] [python] - OpenCV Forum: https://forum.opencv.org/
- BGR: OpenCV's default (Blue, Green, Red) - opposite of RGB
- Grayscale: Single channel, values 0-255
- HSV: Hue, Saturation, Value - useful for color-based segmentation
(0,0) -------- x (width) -------->
|
|
y (height)
|
|
v
Pre-trained classifiers using Haar-like features for object detection:
- Fast: Real-time performance
- Trained: Uses machine learning on thousands of images
- Scale-invariant: Detects objects at different sizes
- Parameters:
scaleFactor: How much image size is reduced at each scale (e.g., 1.1 = 10%)minNeighbors: Minimum neighbors for valid detection (higher = fewer false positives)
Selecting a specific area of an image for focused processing:
# Extract face region
roi = image[y:y+h, x:x+w]
# Process only the ROI
eyes = eye_cascade.detectMultiScale(roi)This project is provided for educational purposes. OpenCV itself is released under the Apache 2 License.
Haar Cascade Files: Provided by OpenCV (Apache 2 License)
Arnab
Feel free to:
- Add more examples
- Improve documentation
- Fix bugs
- Suggest new features
- Image Paths: Update paths in scripts to match your local file structure
- Webcam Index: Default is
0; change if you have multiple cameras - Performance: Real-time detection performance depends on CPU speed and image resolution
- Cascade Selection: Use
haarcascade_frontalface_default.xmlfor human face detection instead of cat faces
- Python 3.7+ installed
- Virtual environment created and activated
- Dependencies installed (
pip install -r requirements.txt) - OpenCV version verified
- Sample images available (or update paths)
- Webcam connected and functional
- Cascade XML files in project directory
Happy Coding! π
Explore the fascinating world of computer vision with OpenCV!