A real-time motion detection system built with OpenCV, tracking iterative improvements from a simple baseline to adaptive background modeling.
This project detects moving objects in a live webcam feed by comparing frames and flagging regions with significant pixel-level change. It's built as a learning project to demonstrate progression from a naive technique to a more robust, production-style approach.
The initial approach: captures a single reference frame at startup and compares every subsequent frame against it using absolute differencing and a fixed global threshold.
Limitations identified:
- Reference frame never updates — fragile to lighting changes or scene drift
- Fixed global threshold with no adaptive modeling
- No shadow handling
File: src/detector_v1.py
Replaces the static reference frame with cv2.createBackgroundSubtractorMOG2, a Gaussian Mixture Model that continuously updates its background estimate per pixel.
Improvements:
- Background model adapts to gradual lighting/scene changes
- Adaptive per-pixel thresholding instead of one fixed global value
- Built-in shadow detection and filtering
- Corrected area-filter logic (flags large contours, not small noise)
File: src/detector_v2.py
- Python 3
- OpenCV (
cv2) - imutils
git clone https://github.com/<your-username>/moving-object-detection.git
cd moving-object-detection
pip install -r requirements.txtRun the latest version:
python src/detector_v2.pyOr run the original baseline for comparison:
python src/detector_v1.pyPress q to quit the camera feed window.
- Capture frame from webcam, resize and convert to grayscale
- Apply MOG2 background subtractor to get a foreground mask
- Threshold out shadow pixels, dilate to merge nearby regions
- Find contours in the mask; filter by area to ignore small noise
- Draw bounding boxes around detected moving objects
- Multi-object tracking with unique IDs (e.g. centroid tracking or
cv2.TrackerAPIs) - Save/export detection events with timestamps
- Optional deep learning-based detection (e.g. YOLO) as a v3 comparison
MIT — see LICENSE