Skip to content

NeuralNik/threat-detection-system

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

1 Commit
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿ›ก๏ธ Enhanced Threat Detection System

Python YOLOv8 License Accuracy

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.

Threat Detection Demo

๐Ÿš€ Key Features

๐ŸŽฏ Detection Capabilities

  • 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

๐Ÿค– AI Performance

  • 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

๐Ÿ“Š Advanced Analytics

  • 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

๐Ÿ”ง Technical Features

  • 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

๐Ÿ“ Project Structure

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

๐Ÿ› ๏ธ Installation & Setup

Prerequisites

  • 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+

Step 1: Clone the Repository

git clone https://github.com/yourusername/enhanced-threat-detection.git
cd enhanced-threat-detection

Step 2: Create Virtual Environment

# Create virtual environment
python -m venv .venv

# Activate virtual environment
# On Windows:
.venv\Scripts\activate

# On Linux/macOS:
source .venv/bin/activate

Step 3: Install Dependencies

# Upgrade pip to latest version
pip install --upgrade pip

# Install required packages
pip install -r requirements.txt

Step 4: Verify Installation

# Test the installation
python -c "import torch; import cv2; import ultralytics; print('โœ… Installation successful!')"

๐Ÿš€ Quick Start Guide

Option 1: Real-time Camera Detection

python enhanced_threat_detector.py
# Select: 1. ๐Ÿ“ท Real-time camera detection
# Follow the prompts to configure camera settings

Option 2: Video File Analysis

python enhanced_threat_detector.py
# Select: 2. ๐ŸŽฌ Video file detection
# Enter the path to your video file
# Configure output options (save video/logs)

Option 3: Single Image Analysis

python enhanced_threat_detector.py
# Select: 3. ๐Ÿ–ผ๏ธ Single image detection
# Enter the path to your image file
# View results and save annotated image

Option 4: Model Information

python enhanced_threat_detector.py
# Select: 4. โ„น๏ธ Model information
# View detailed model specifications and performance metrics

๐Ÿ“Š Usage Examples

Example 1: Security Camera Monitoring

from 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)

Example 2: Analyze Security Footage

# 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
)

Example 3: Batch Image Processing

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}%")

๐Ÿ“‹ Sample Output

Threat Detection Summary

๐Ÿ“Š 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
==================================================

๐Ÿ”„ Model Training

Training on Custom Dataset

# 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

Training Features

  • 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

Dataset Requirements

  • 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/
    

๐ŸŽ›๏ธ Configuration & Customization

Threat Level Customization

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
}

Detection Parameters

# 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

Camera Settings

# 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

๐Ÿ“ˆ Performance Metrics

Model Performance

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

System Requirements

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

๐Ÿ“‹ Dependencies

Core Libraries

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

Optional Dependencies

# 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

๐Ÿ”’ Security & Ethical Considerations

โš ๏ธ Important Security Notes

  • 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

โœ… Recommended Use Cases

  • 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

โŒ Not Recommended For

  • Standalone automated decision-making systems
  • Unsupervised law enforcement applications
  • Privacy-invasive surveillance without consent
  • Any application without human oversight

๐Ÿ›ก๏ธ Best Practices

  1. Always combine with human judgment
  2. Implement proper access controls
  3. Maintain audit logs of system usage
  4. Regular system accuracy validation
  5. Clear privacy policies and user consent
  6. Staff training on system limitations

๐Ÿ› Troubleshooting

Common Issues & Solutions

Camera Not Detected

# 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

Low Detection Accuracy

  • Ensure good lighting conditions
  • Check camera focus and positioning
  • Verify objects are clearly visible
  • Adjust confidence threshold if needed

Performance Issues

# 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

Import Errors

# Reinstall dependencies
pip uninstall torch torchvision opencv-python ultralytics
pip install -r requirements.txt

# Check Python version compatibility
python --version  # Should be 3.8+

Memory Issues

  • Close other applications to free RAM
  • Reduce batch size in training configuration
  • Process smaller video segments
  • Use lower resolution inputs

๐Ÿค Contributing

We welcome contributions from the community! Please see our CONTRIBUTING.md file for detailed guidelines.

Quick Contribution Guide

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Areas for Contribution

  • ๐Ÿ› Bug fixes and improvements
  • โœจ New detection features
  • ๐Ÿ“š Documentation enhancements
  • ๐Ÿš€ Performance optimizations
  • ๐Ÿงช Testing and validation
  • ๐ŸŒ Internationalization

๐Ÿ“„ License

This project is licensed under the MIT License with additional security and ethical use clauses. See the LICENSE file for complete details.

License Summary

  • โœ… 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

๐Ÿ”„ Changelog & Roadmap

Recent Updates (v2.0)

  • โœ… Enhanced video processing with progress tracking
  • โœ… Comprehensive threat analysis and reporting
  • โœ… CPU optimization improvements
  • โœ… Multi-format video support
  • โœ… Professional documentation

Upcoming Features (v2.1)

  • ๐Ÿ”„ Multi-camera simultaneous monitoring
  • ๐Ÿ”„ Cloud deployment options and APIs
  • ๐Ÿ”„ Mobile app integration
  • ๐Ÿ”„ Advanced analytics dashboard
  • ๐Ÿ”„ Real-time alert notification system

Long-term Roadmap

  • ๐Ÿ”ฎ Integration with security management systems
  • ๐Ÿ”ฎ Edge device deployment capabilities
  • ๐Ÿ”ฎ Advanced threat prediction algorithms
  • ๐Ÿ”ฎ Multi-language user interface
  • ๐Ÿ”ฎ Custom training web interface

๐Ÿ†˜ Support & Community

Getting Help

Community Guidelines

  • Be respectful and inclusive
  • Help others learn and contribute
  • Follow our code of conduct
  • Share knowledge and experiences

๐Ÿ“ž Contact Information

๐Ÿ™ Acknowledgments

  • 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

๐Ÿ“Š Repository Statistics

GitHub stars GitHub forks GitHub issues GitHub pull requests

โš ๏ธ Disclaimer: This software is provided for educational and legitimate security purposes only. Users are responsible for ensuring compliance with applicable laws and regulations. The authors assume no liability for misuse of this software.

๐Ÿ›ก๏ธ 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.

About

No description, website, or topics provided.

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages