A real-time color-based object detection and tracking system built with Python and OpenCV. Supports 5 switchable detection modes, multi-object tracking, motion trail visualization, and a live HSV tuning interface.
- 5 Detection Modes — Green, Red, Blue, Multi (all 3 simultaneously), and Custom HSV slider mode
- Dual-range red masking — handles red's hue wrapping at 0°/180° in HSV color space
- 30-point motion trail — visualizes object movement history per color channel
- 3-step mask cleaning pipeline — median blur → morphological open → morphological close for noise-robust detection
- Live HSV tuner — interactive trackbar controls to dial in custom color ranges in real time
- Contour-based tracking — bounding boxes and center-point labels rendered on the largest detected contour per color
| Mode | Description |
|---|---|
S |
Custom HSV slider mode — tune your own color range live |
G |
Green object tracking |
R |
Red object tracking (dual-range HSV) |
B |
Blue object tracking |
M |
Multi-color mode — tracks Green, Red, and Blue simultaneously |
Each frame is converted from BGR to HSV, which separates color (hue) from lighting (value) — making detection far more robust under changing light conditions than RGB.
- Green and Blue use a single HSV range via
cv2.inRange() - Red uses two ranges combined with bitwise OR, since red straddles the 0°/180° boundary in the HSV hue wheel
Each mask goes through a 3-step pipeline:
Median Blur (5x5) → removes salt-and-pepper noise
Morphological Open → eliminates small false-positive blobs
Morphological Close → fills small holes inside detected regions
- Contours are extracted with
cv2.findContours() - The largest contour is selected as the tracked object
- A bounding box and color label are drawn around it
- The center point is appended to a rolling 30-point trail, drawn as connected line segments
Color-Based-Object-Tracking/
├── main.py # Main application loop
git clone https://github.com/VidhanGupta-01/Color-Based-Object-Tracking.git
cd Color-Based-Object-Tracking
pip install opencv-python numpypython main.pyOnce running, use keyboard shortcuts to switch modes:
| Key | Action |
|---|---|
S |
Switch to HSV slider (custom) mode |
G |
Switch to green tracking mode |
R |
Switch to red tracking mode |
B |
Switch to blue tracking mode |
M |
Switch to multi-color tracking mode |
Q |
Quit |
Three windows will open:
- Original — live feed with tracking overlay
- HSV — raw HSV frame
- Mask — current active detection mask
opencv-python
numpy
A working webcam is required.
- Python 3
- OpenCV — camera capture, HSV conversion, contour detection, drawing
- NumPy — array operations for HSV range definitions