A deep learning-based system for detecting and tracking drones in video feeds using YOLOv8 Nano and PyTorch, optimized for Apple Silicon (M4 chip) with MPS support.
This project implements a real-time drone detection and tracking system using:
- YOLOv8 Nano - Lightweight object detection model
- PyTorch with MPS - Optimized for Apple Silicon
- Norfair Tracker - Multi-object tracking (optional)
- OpenCV - Video processing and visualization
- β Real-time drone detection in video/webcam feeds
- β Multi-object tracking with unique IDs
- β Optimized for Apple Silicon (MPS backend)
- β Configurable confidence thresholds
- β Support for video files and webcam input
- β Clean, modular codebase with detailed comments
Counter Drone Detection & Tracking/
βββ train_model.py # Training script
βββ detect_video.py # Detection script (video/webcam)
βββ track_video.py # Tracking script with Norfair
βββ organize_dataset.py # Dataset organization script
βββ test_camera.py # Camera test utility
βββ create_test_video.py # Create test video from dataset
βββ data.yaml # Dataset configuration
βββ requirements.txt # Python dependencies
βββ README.md # This file
βββ Drone Dataset/
β βββ drone_dataset_yolo/
β βββ images/
β β βββ train/
β β βββ valid/
β βββ labels/
β βββ train/
β βββ valid/
βββ runs/
βββ train/
βββ counter_drone/
βββ weights/
βββ best.pt
βββ last.pt
- Python 3.10 or higher
- macOS with Apple Silicon (M1/M2/M3/M4)
- VS Code (recommended)
# Navigate to project directory
cd "Counter Drone Detection & Tracking"
# Create virtual environment
python3 -m venv venv
# Activate virtual environment
source venv/bin/activate
# IMPORTANT: Make sure you see (venv) in your prompt
# If you see (base) or other conda environments, deactivate them first:
# conda deactivate # If using conda# Make sure virtual environment is activated (you should see (venv) in prompt)
# If not, activate it: source venv/bin/activate
# Upgrade pip
pip install --upgrade pip
# Install PyTorch with MPS support (for Apple Silicon)
pip install torch torchvision
# Install other dependencies (this will install NumPy < 2.0 for compatibility)
pip install -r requirements.txt
# Verify NumPy version (should be < 2.0)
python -c "import numpy; print('NumPy version:', numpy.__version__)"# Check PyTorch MPS availability
python3 -c "import torch; print('MPS available:', torch.backends.mps.is_available())"Ensure your dataset follows this structure:
Drone Dataset/drone_dataset_yolo/
βββ images/
β βββ train/ # Training images
β βββ valid/ # Validation images
βββ labels/
βββ train/ # Training labels (YOLO format)
βββ valid/ # Validation labels (YOLO format)
If your dataset is in a single folder (e.g., dataset_txt/), use the organization script to split it into train/valid:
# Organize dataset into train/valid splits (80/20)
python organize_dataset.py
# Custom options
python organize_dataset.py --source "Drone Dataset/drone_dataset_yolo/dataset_txt" --target "Drone Dataset/drone_dataset_yolo" --train-ratio 0.8This script will:
- Split images and labels into train/valid sets (80/20 by default)
- Create the required folder structure
- Copy files to appropriate directories
- Maintain image-label pairs
Each image should have a corresponding .txt file with the same name. Label format:
class_id center_x center_y width height
All coordinates are normalized (0-1). Example:
0 0.5 0.5 0.2 0.3
Update data.yaml if your dataset path is different:
path: ./Drone Dataset/drone_dataset_yolo
train: images/train
val: images/valid
nc: 1 # Number of classes
names:
0: drone# Activate virtual environment (if not already active)
source venv/bin/activate
# Run training
python train_model.pyThe training script (train_model.py) is configured with:
- Model: YOLOv8 Nano (
yolov8n.pt) - Epochs: 40
- Image Size: 640x640
- Batch Size: 16 (adjust based on available memory)
- Device: Automatically detects MPS/CPU
After training, the best model will be saved at:
runs/train/counter_drone/weights/best.pt
Training results (plots, metrics) will be available in:
runs/train/counter_drone/
# Detect drones in a video file
python detect_video.py --source test.mp4 --conf 0.25
# Use custom model
python detect_video.py --model runs/train/counter_drone/weights/best.pt --source test.mp4# Use default webcam (index 0)
python detect_video.py --source 0
# Use specific webcam
python detect_video.py --source 1--model: Path to model weights (default:runs/train/counter_drone/weights/best.pt)--source: Video file path or webcam index (default:0)--conf: Confidence threshold 0-1 (default:0.25)
- Press
qto quit - Press
sto save current frame
# Track drones in a video file
python track_video.py --source test.mp4 --conf 0.25
# Track from webcam
python track_video.py --source 0- Unique IDs: Each detected drone gets a unique ID
- Trails: Visual trails show drone movement paths
- Color Coding: Different colors for different tracks
- Bounding Boxes: Detection boxes with confidence scores
If you want to use the advanced tracking features:
pip install norfairIf Norfair is not installed, the script will use a simple tracking fallback.
# 1. Organize dataset (if not already organized)
python organize_dataset.py
# 2. Train the model
python train_model.py
# 3. Test on video file
python detect_video.py --source test.mp4
# 4. Test with tracking
python track_video.py --source test.mp4# Detect drones from webcam
python detect_video.py --source 0 --conf 0.3
# Track drones from webcam
python track_video.py --source 0 --conf 0.3# Create a test video from validation images
python create_test_video.py
# Custom options
python create_test_video.py --output my_test_video.mp4 --fps 15 --duration 10
# Then use it for detection
python detect_video.py --source my_test_video.mp4# Higher confidence (fewer false positives)
python detect_video.py --source test.mp4 --conf 0.5
# Lower confidence (more detections)
python detect_video.py --source test.mp4 --conf 0.15# List all accessible cameras
python test_camera.py --list
# Test specific camera
python test_camera.py --camera 0Solution: Make sure you're using PyTorch 2.0+ and macOS 12.3+ with Apple Silicon.
pip install --upgrade torch torchvisionSolution: Check that data.yaml points to the correct dataset path and the folder structure matches the expected format.
Solution: Reduce batch size in train_model.py:
BATCH_SIZE = 8 # or lowerSolution:
- Make sure the video file path is correct
- Use absolute path instead of relative path
- Verify file exists:
ls -la path/to/video.mp4 - Check file format is supported (MP4, AVI, MOV, MKV)
- Try a different video file to rule out corruption
- Example:
python detect_video.py --source /absolute/path/to/video.mp4
Error Message:
A module that was compiled using NumPy 1.x cannot be run in NumPy 2.3.3
AttributeError: _ARRAY_API not found
Solution:
This happens when using conda base environment with NumPy 2.x. Fix it:
-
Use Virtual Environment (NOT conda base):
# Deactivate conda if active conda deactivate # Activate venv (you should see (venv) not (base)) source venv/bin/activate
-
Fix NumPy Version:
# Option 1: Use the fix script ./fix_numpy_issue.sh # Option 2: Manual fix pip uninstall numpy opencv-python opencv-contrib-python -y pip install -r requirements.txt
-
Verify:
python -c "import numpy; print('NumPy:', numpy.__version__)" # Should be 1.x.x python -c "import cv2; print('OpenCV:', cv2.__version__)" # Should work
Solution:
-
macOS Camera Permissions:
- Go to System Settings > Privacy & Security > Camera
- Enable camera access for:
- Terminal (if running from terminal)
- Python (if available in the list)
- VS Code (if running from VS Code)
- Restart Terminal/VS Code after enabling permissions
- Test camera access:
python test_camera.py --list
-
Test Camera Access:
# List all accessible cameras python test_camera.py --list # Test specific camera python test_camera.py --camera 0
-
Other Solutions:
- Try different webcam indices (0, 1, 2, etc.)
- Make sure no other application is using the webcam
- Use a video file instead:
python detect_video.py --source video.mp4
- Training: Use MPS backend for faster training on Apple Silicon
- Inference: Reduce image size for faster processing
- Tracking: Adjust
distance_thresholdintrack_video.pyfor better tracking - Confidence: Tune confidence threshold based on your use case
Feel free to submit issues, fork the repository, and create pull requests for any improvements.
This project is open source and available for educational and research purposes.
Built for Counter-Drone Detection and Tracking System
- Ultralytics for YOLOv8
- PyTorch team for MPS support
- Norfair for tracking capabilities
Happy Drone Detecting! π