A state-of-the-art AI-powered threat detection system designed for real-time identification of firearms and weapons using computer vision. Built with YOLOv8 and optimized for CPU inference, this system provides comprehensive threat assessment capabilities for security applications.
- Real-time Camera Monitoring: Live threat detection through webcam or IP cameras
- Video File Analysis: Comprehensive analysis of pre-recorded security footage
- Single Image Processing: Instant threat assessment for static images
- Multi-format Support: Compatible with MP4, AVI, MOV, JPG, PNG formats
- Custom-trained Model: Specialized YOLOv8 model for firearm identification
- High Accuracy: 84.8% mAP50, 84.6% Recall, 77.6% Precision
- Fast Inference: 30-60ms processing time per frame
- Lightweight: 5.9MB model size for efficient deployment
- CPU Optimized: No GPU required, runs on standard hardware
- Threat Level Assessment: Intelligent scoring system (0-100% threat level)
- Comprehensive Reports: Detailed session analysis with statistics
- Critical Incident Logging: Automatic documentation of high-threat events
- Performance Monitoring: Real-time FPS and detection rate tracking
- Export Capabilities: JSON logs, annotated videos, screenshots
- Cross-platform: Windows, Linux, macOS compatible
- Modular Design: Easy to extend and customize
- Professional Interface: Interactive menu system with multiple detection modes
- Batch Processing: Efficient handling of large video files
enhanced-threat-detection/
โโโ ๐ README.md # This file
โโโ ๐ง enhanced_threat_detector.py # Main detection system (Entry Point)
โโโ ๐ train_guns_optimized.py # Model training script
โโโ ๐ฅ dataset_downloader_weapons.py # Dataset acquisition utility
โโโ ๐ค guns_detector_cpu_optimized.pt # Pre-trained model (5.9MB)
โโโ ๐ requirements.txt # Python dependencies
โโโ ๐ LICENSE # MIT License
โโโ ๐ค CONTRIBUTING.md # Contribution guidelines
โโโ ๐ .gitignore # Git ignore rules
โโโ ๐ ENHANCED_THREAT_DETECTOR_FEATURES.md # Detailed feature documentation
โโโ ๐ผ๏ธ gun_detection_test_1.jpg # Demo image - Handgun detection
โโโ ๐ผ๏ธ gun_detection_test_2.jpg # Demo image - Multiple weapons
โโโ ๐ผ๏ธ gun_detection_test_3.jpg # Demo image - Low light conditions
โโโ ๐ datasets/ # Training datasets directory
โโโ guns-object-detection/ # Original gun dataset (333 images)
โโโ guns_yolo_format/ # YOLO formatted training data
- Python: 3.8 or higher (Recommended: Python 3.9+)
- Memory: 4GB RAM minimum (8GB recommended)
- Storage: 2GB free disk space
- Camera: USB webcam or IP camera (for real-time detection)
- OS: Windows 10+, Ubuntu 18.04+, macOS 10.14+
git clone https://github.com/yourusername/enhanced-threat-detection.git
cd enhanced-threat-detection# Create virtual environment
python -m venv .venv
# Activate virtual environment
# On Windows:
.venv\Scripts\activate
# On Linux/macOS:
source .venv/bin/activate# Upgrade pip to latest version
pip install --upgrade pip
# Install required packages
pip install -r requirements.txt# Test the installation
python -c "import torch; import cv2; import ultralytics; print('โ
Installation successful!')"python enhanced_threat_detector.py
# Select: 1. ๐ท Real-time camera detection
# Follow the prompts to configure camera settingspython enhanced_threat_detector.py
# Select: 2. ๐ฌ Video file detection
# Enter the path to your video file
# Configure output options (save video/logs)python enhanced_threat_detector.py
# Select: 3. ๐ผ๏ธ Single image detection
# Enter the path to your image file
# View results and save annotated imagepython enhanced_threat_detector.py
# Select: 4. โน๏ธ Model information
# View detailed model specifications and performance metricsfrom enhanced_threat_detector import ThreatDetector
# Initialize the threat detection system
detector = ThreatDetector()
# Start real-time monitoring with logging
detector.run_camera_detection(camera_id=0, save_detections=True)# Process a security video file
detector.run_video_detection(
video_path="security_footage.mp4",
save_output=True, # Save annotated video
save_detections=True # Save detection logs
)import cv2
# Process multiple images
for image_path in ["image1.jpg", "image2.jpg", "image3.jpg"]:
image = cv2.imread(image_path)
annotated_image, detections, threat_level = detector.detect_threats(image)
print(f"{image_path}: {len(detections)} threats detected, max threat: {threat_level}%")๐ THREAT DETECTION SUMMARY
==================================================
๐ Session Duration: 45.2 seconds
๐น Total Frames Processed: 1,356
โ ๏ธ Frames with Detections: 23
๐ฏ Total Objects Detected: 31
๐ Average Threat Level: 67.3%
๐จ Maximum Threat Level: 95%
๐ฅ THREAT LEVEL BREAKDOWN:
๐ด High Threat (โฅ80%): 18 frames
๐ Medium Threat (50-79%): 3 frames
๐ก Low Threat (20-49%): 2 frames
๐ฏ DETECTED OBJECTS:
gun: 28 detections (Avg: 94.2%, Max: 95%)
knife: 3 detections (Avg: 83.7%, Max: 85%)
๐จ CRITICAL INCIDENTS (โฅ80% Threat):
14:30:15 - Threat: 95% - Objects: gun
14:30:18 - Threat: 95% - Objects: gun
14:30:22 - Threat: 85% - Objects: knife
๐ก RECOMMENDATIONS:
๐จ IMMEDIATE ACTION REQUIRED - Very high threat detected
โก PERFORMANCE STATS:
Average FPS: 30.0
Detection Rate: 1.7% of frames
==================================================
# Train with your own dataset
python train_guns_optimized.py
# The script will automatically:
# 1. Analyze your system specifications
# 2. Optimize training parameters for CPU
# 3. Convert dataset formats if needed
# 4. Train the model with progress monitoring
# 5. Save the trained model- Automatic Format Conversion: Supports YOLO, Pascal VOC, COCO formats
- CPU Optimization: Intelligent parameter tuning for CPU training
- Progress Monitoring: Real-time training metrics and validation scores
- Early Stopping: Prevents overfitting with intelligent stopping criteria
- System Analysis: Automatically detects and optimizes for your hardware
- Images: JPG, PNG, or other common formats
- Annotations: YOLO txt files, XML files, or JSON annotations
- Minimum Size: 100+ images recommended (current model trained on 333 images)
- Directory Structure:
your_dataset/ โโโ images/ โ โโโ train/ โ โโโ val/ โ โโโ test/ โโโ labels/ โโโ train/ โโโ val/ โโโ test/
Edit threat levels in enhanced_threat_detector.py:
self.threat_levels = {
'gun': 95, # Firearms - Critical threat
'knife': 85, # Bladed weapons - High threat
'rifle': 98, # Rifles - Maximum threat
'pistol': 95, # Handguns - Critical threat
'scissors': 40, # Potential weapons - Medium threat
'unknown': 10 # Default - Very low threat
}# Adjust model confidence and IoU thresholds
self.model.conf = 0.3 # Confidence threshold (0-1)
self.model.iou = 0.5 # IoU threshold for Non-Maximum Suppression# Customize camera properties
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) # Frame width
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) # Frame height
cap.set(cv2.CAP_PROP_FPS, 30) # Frames per second| Metric | Value | Description |
|---|---|---|
| mAP50 | 84.8% | Mean Average Precision at IoU=0.5 |
| Recall | 84.6% | Percentage of actual threats detected |
| Precision | 77.6% | Percentage of detections that are correct |
| Model Size | 5.9MB | Compact model for efficient deployment |
| Inference Speed | 30-60ms | Processing time per frame (CPU) |
| Training Time | 41 minutes | On Intel i7-1255U processor |
| Component | Minimum | Recommended |
|---|---|---|
| CPU | Intel i5 / AMD Ryzen 5 | Intel i7 / AMD Ryzen 7 |
| RAM | 4GB | 8GB+ |
| Storage | 2GB free space | 5GB+ free space |
| Camera | 720p USB webcam | 1080p camera |
| OS | Windows 10, Ubuntu 18.04, macOS 10.14 | Latest versions |
ultralytics>=8.0.0 # YOLOv8 framework
opencv-python>=4.8.0 # Computer vision operations
torch>=2.0.0 # Deep learning framework
numpy>=1.24.0 # Numerical computing
Pillow>=9.5.0 # Image processing
PyYAML>=6.0 # Configuration file handling
psutil>=5.9.0 # System and process monitoring# For GPU acceleration (optional)
torch-gpu>=2.0.0
# For advanced image processing
scikit-image>=0.19.0
# For data analysis
pandas>=1.5.0
matplotlib>=3.6.0- Professional Use Only: Designed for legitimate security applications
- Human Oversight Required: Never use as sole basis for security decisions
- Privacy Compliance: Ensure compliance with local privacy laws
- Ethical Deployment: Use responsibly and transparently
- Security checkpoint monitoring and screening
- Building access control and perimeter security
- Event security enhancement and crowd monitoring
- Training simulations and educational purposes
- Research and development in security technology
- Standalone automated decision-making systems
- Unsupervised law enforcement applications
- Privacy-invasive surveillance without consent
- Any application without human oversight
- Always combine with human judgment
- Implement proper access controls
- Maintain audit logs of system usage
- Regular system accuracy validation
- Clear privacy policies and user consent
- Staff training on system limitations
# Check camera permissions and availability
python -c "import cv2; cap = cv2.VideoCapture(0); print('Camera available:', cap.isOpened())"
# Try different camera IDs
python enhanced_threat_detector.py
# Select camera detection and try camera IDs: 0, 1, 2- Ensure good lighting conditions
- Check camera focus and positioning
- Verify objects are clearly visible
- Adjust confidence threshold if needed
# Reduce image resolution for faster processing
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)
# Lower detection confidence for fewer false positives
self.model.conf = 0.5# Reinstall dependencies
pip uninstall torch torchvision opencv-python ultralytics
pip install -r requirements.txt
# Check Python version compatibility
python --version # Should be 3.8+- Close other applications to free RAM
- Reduce batch size in training configuration
- Process smaller video segments
- Use lower resolution inputs
We welcome contributions from the community! Please see our CONTRIBUTING.md file for detailed guidelines.
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- ๐ Bug fixes and improvements
- โจ New detection features
- ๐ Documentation enhancements
- ๐ Performance optimizations
- ๐งช Testing and validation
- ๐ Internationalization
This project is licensed under the MIT License with additional security and ethical use clauses. See the LICENSE file for complete details.
- โ Commercial and personal use permitted
- โ Modification and distribution allowed
- โ Private use encouraged
โ ๏ธ Must include license and copyright noticeโ ๏ธ Must comply with security and ethical guidelines
- โ Enhanced video processing with progress tracking
- โ Comprehensive threat analysis and reporting
- โ CPU optimization improvements
- โ Multi-format video support
- โ Professional documentation
- ๐ Multi-camera simultaneous monitoring
- ๐ Cloud deployment options and APIs
- ๐ Mobile app integration
- ๐ Advanced analytics dashboard
- ๐ Real-time alert notification system
- ๐ฎ Integration with security management systems
- ๐ฎ Edge device deployment capabilities
- ๐ฎ Advanced threat prediction algorithms
- ๐ฎ Multi-language user interface
- ๐ฎ Custom training web interface
- ๐ Documentation: Check ENHANCED_THREAT_DETECTOR_FEATURES.md
- ๐ Bug Reports: GitHub Issues
- ๐ฌ Discussions: GitHub Discussions
- ๐ง Contact: [[email protected]]
- Be respectful and inclusive
- Help others learn and contribute
- Follow our code of conduct
- Share knowledge and experiences
- GitHub: @yourusername
- Email: [[email protected]]
- LinkedIn: [Your LinkedIn Profile]
- Project Homepage: [Project Website]
- Ultralytics Team for the excellent YOLOv8 framework
- OpenCV Community for computer vision tools
- PyTorch Team for the deep learning framework
- Contributors who helped improve this project
- Security Researchers who provided feedback and guidance
๐ก๏ธ Security Notice: This system is designed to assist human security professionals and should never be used as the sole basis for security decisions. Always combine automated detection with human oversight and judgment.
