Real-time hand gesture recognition and automation system using OpenCV, Python, and machine learning (CNN & SVM).
Modern Architecture
- Clean, modular code structure
- Proper error handling and logging
- Configuration management
- Type hints for better IDE support
Multiple Recognition Modes
- SVM Mode: Real-time gesture detection for action automation
- Segmentation Mode: Hand tracking and finger counting
Machine Learning
- CNN (Convolutional Neural Network) for gesture classification
- SVM (Support Vector Machine) for gesture detection
- Easy model training and evaluation
Performance
- Frame downsampling for faster processing
- FPS counter and monitoring
- Multi-threaded camera reading
- Optimized detection pipeline
Automation
- Automatic keyboard actions
- Mouse control integration
- Customizable gesture-to-action mapping
- Action cooldown to prevent spam
gesture-recognition-actions/
├── config.py # Centralized configuration
├── utils.py # Helper utilities and classes
├── train_cnn.py # CNN model training
├── gesture_detector.py # SVM-based gesture detection
├── hand_segmentation.py # Hand segmentation utilities
├── app.py # Main application
├── preprocessing/ # Legacy preprocessing scripts
├── models/ # Trained models
├── datasets/ # Training datasets
├── requirements.txt # Python dependencies
└── README.md # This file
- Python 3.8 or higher
- Webcam connected to your computer
- macOS, Linux, or Windows
- Clone the repository
cd /path/to/gesture-recognition-actions- Create virtual environment (recommended)
python3 -m venv venv
source venv/bin/activate # macOS/Linux
# or
venv\Scripts\activate # Windows- Install dependencies
pip install -r requirements.txtEdit config.py to customize:
CAMERA_ID = 0 # Camera device ID (0=default, 1=external)
CAMERA_WIDTH = 1280
CAMERA_HEIGHT = 720
SCALE_FACTOR = 4 # For downsampling framesConfigure gesture-to-action mapping:
GESTURE_ACTIONS = {
"Pause": ("press", "space"),
"Scrolling Up": ("scroll", -7),
"Scrolling Tabs": ("hotkey", ("ctrl", "pgup")),
"Change Program": ("hotkey", ("alt", "tab")),
}SVM_CONFIDENCE_THRESHOLD = 0.90 # 90% minimum confidence
COOLDOWN_MS = 500 # Milliseconds between actionsTo train a new CNN gesture model:
python train_cnn.pyRequirements:
- Dataset organized in
datasets/Below_CAM/with subdirectories per gesture - Directory structure:
datasets/Below_CAM/A/,datasets/Below_CAM/C/, etc.
Configuration:
CNN_EPOCHS = 20
CNN_BATCH_SIZE = 32
CNN_IMAGE_SIZE = (300, 300)Detect hand gestures and perform actions:
python app.py --mode svm --camera 0Features:
- Real-time gesture detection
- Automatic action execution
- FPS monitoring
- Confidence score display
Controls:
- Press 'q' to quit the application
Track hand and count fingers:
python app.py --mode segment --camera 0Features:
- Automatic background calibration (30 frames)
- Finger counting
- Hand contour visualization
- Hand size and center tracking
Main application class:
from app import GestureRecognitionApp
# Create app instance
app = GestureRecognitionApp(use_svm=True)
# Setup and run
app.setup()
app.run(mode="svm")
app.cleanup()
# Or use context manager
with GestureRecognitionApp() as app:
app.run(mode="svm")Gesture detection using SVM models:
from gesture_detector import SVMGestureDetector
detector = SVMGestureDetector()
# Detect gestures in frame
detections = detector.detect_gestures(frame, scale_factor=4)
# Draw detection boxes
frame = detector.draw_detections(frame, detections)
# Perform actions
for detection_dict, gesture_idx, confidence in detections:
gesture_name = detector.gesture_names[gesture_idx]
detector.perform_action(gesture_name)Hand segmentation and finger counting:
from hand_segmentation import HandSegmenter, ROI, process_frame_for_segmentation
segmenter = HandSegmenter()
roi = ROI()
# Process frame
roi_frame = process_frame_for_segmentation(frame, roi)
# Update background (calibration phase)
segmenter.update_background(roi_frame)
# Segment hand
result = segmenter.segment_hand(roi_frame)
if result:
thresholded, hand_contour = result
# Count fingers
finger_count = segmenter.count_fingers(thresholded, hand_contour)Manage webcam operations:
from utils import CameraManager
# Manual usage
camera = CameraManager(camera_id=0, width=1280, height=720)
camera.open()
success, frame = camera.read_frame()
camera.release()
# Context manager (recommended)
with CameraManager(camera_id=0) as camera:
success, frame = camera.read_frame()Monitor frames per second:
from utils import FpsCounter
fps_counter = FpsCounter(update_interval=30)
while True:
fps = fps_counter.update()
print(f"Current FPS: {fps:.2f}")# Check available cameras
import cv2
for i in range(5):
cap = cv2.VideoCapture(i)
if cap.isOpened():
print(f"Camera {i} is available")
cap.release()
# Use correct camera ID in config
config.CAMERA_ID = 1 # or your camera IDERROR: File not found: models/Pause_detector.svm
- Ensure SVM models are in the
models/directory - Download pre-trained models or train your own
- Improve lighting - Ensure adequate, consistent lighting
- Train custom models - Use your own gesture data
- Adjust threshold - Lower
SVM_CONFIDENCE_THRESHOLDfor sensitivity - Scale factor - Use
SCALE_FACTOR = 2for faster but less accurate detection
- Check
config.GESTURE_ACTIONSmapping - Verify gesture confidence is above
SVM_CONFIDENCE_THRESHOLD - Check action cooldown:
COOLDOWN_MS - Ensure PyAutoGUI has permission (macOS may require accessibility permissions)
# In config.py
SCALE_FACTOR = 4 # More downsampling = faster
SVM_UPSAMPLE_NUM_TIMES = 0 # Less upsampling = faster
DISPLAY_FPS = True # Monitor FPSSCALE_FACTOR = 2 # Less downsampling = more accurate
SVM_CONFIDENCE_THRESHOLD = 0.95 # Higher threshold- Architecture: 3 Convolutional layers + 2 Dense layers
- Input: 300x300 grayscale images
- Output: 17 gesture classes
- Loss: Sparse categorical crossentropy
- Optimizer: Adam
- Feature: HOG (Histogram of Oriented Gradients)
- Type: dlib FHOG object detector
- Training: One-vs-All classification
- opencv-python - Computer vision
- tensorflow - Deep learning framework
- scikit-learn - Machine learning utilities
- dlib - Object detection (SVM)
- numpy - Numerical computing
- pyautogui - GUI automation
- imutils - Image utilities
- matplotlib - Visualization
- PEP 8 compliant
- Type hints throughout
- Comprehensive docstrings
- Proper logging
-
Collect training data
- Create subdirectory in
datasets/Below_CAM/NEW_GESTURE/ - Add gesture images
- Create subdirectory in
-
Update config
CNN_GESTURE_NAMES = ["A", "C", ..., "NEW_GESTURE"]
-
Train model
python train_cnn.py
-
Update gesture actions (optional)
GESTURE_ACTIONS["NEW_GESTURE"] = ("hotkey", ("alt", "n"))
Application logs are written to gesture_recognition.log:
2024-01-15 10:30:45,123 - app - INFO - Application setup completed
2024-01-15 10:30:46,456 - gesture_detector - INFO - Loaded model: pause from models/Pause_detector.svm
Configure logging in config.py:
LOG_LEVEL = logging.INFO
LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
LOG_FILE = "gesture_recognition.log"On MacBook Pro (M1):
- SVM Detection: ~45-60 FPS (with 4x downsampling)
- Finger Counting: ~30-40 FPS
- CNN Prediction: ~100 FPS (GPU-accelerated with TensorFlow)
MIT License - see LICENSE file for details
Contributions welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes
- Submit a pull request
Lotfi Habbiche - Software Engineer
- Email: habbichelotfi@gmail.com
- GitHub: habbichelotfi
For issues and questions:
- Check the Troubleshooting section
- Review the API Reference
- Check logs in
gesture_recognition.log - Open an issue on GitHub
- OpenCV for computer vision
- TensorFlow/Keras for deep learning
- dlib for object detection
- scikit-learn for ML utilities