help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
surveillance-video
RSK World
surveillance-video
Surveillance Video Dataset - Security Camera + Person Detection + Anomaly Detection + OpenCV + YOLO
surveillance-video
  • __pycache__
  • annotations
  • config
  • frames
  • models
  • output
  • videos
  • .gitignore713 B
  • GITHUB_DEPLOYMENT.md3.5 KB
  • LICENSE1.3 KB
  • README.md13 KB
  • RELEASE_NOTES.md5.6 KB
  • alert_system.py12 KB
  • analytics.js9.2 KB
  • analytics_dashboard.html9.3 KB
  • api_server.py10.7 KB
  • batch_processor.py8.3 KB
  • config.py1.2 KB
  • create_sample_video.py7.4 KB
  • create_zip.py2.6 KB
  • detect_anomalies.py7.2 KB
  • detect_persons.py6.3 KB
  • download_sample_videos.py2.5 KB
  • extract_frames.py4.5 KB
  • index.html62.2 KB
  • multi_camera_system.py12.5 KB
  • package.json1.2 KB
  • process_video.py4.4 KB
  • project_data.json1.3 KB
  • project_data.php1.6 KB
  • project_data.py1.7 KB
  • requirements.txt372 B
  • script.js6.6 KB
  • setup.py2 KB
  • styles.css13.4 KB
  • surveillance-video.zip1.2 MB
  • train_ml_model.py9 KB
  • verify_project.py5 KB
  • video_quality_analyzer.py9.5 KB
  • video_search.py10.7 KB
detect_persons.py
detect_persons.py
Raw Download
Find: Go to:
# Project: Surveillance Video Dataset
# Author: Molla Samser
# Website: https://rskworld.in/
# Contact: help@rskworld.in
# Phone: +91 93305 39277
# Address: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147

"""
Person detection script using YOLO for surveillance video dataset.
This script detects persons in video frames and saves detection results.
"""

import cv2
import json
import os
from pathlib import Path

try:
    from ultralytics import YOLO
    YOLO_AVAILABLE = True
except ImportError:
    YOLO_AVAILABLE = False
    print("Warning: ultralytics not installed. Install with: pip install ultralytics")


def detect_persons_yolo(video_path, model_path='yolov8n.pt', output_file='annotations/person_detections.json'):
    """
    Detect persons in video using YOLO model.
    
    Args:
        video_path: Path to the input video file
        model_path: Path to YOLO model file
        output_file: Path to save detection results
    """
    if not YOLO_AVAILABLE:
        print("Error: YOLO is not available. Please install ultralytics.")
        return
    
    # Create output directory if it doesn't exist
    os.makedirs(os.path.dirname(output_file) if os.path.dirname(output_file) else '.', exist_ok=True)
    
    # Load YOLO model
    print(f"Loading YOLO model: {model_path}")
    model = YOLO(model_path)
    
    # Open video
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        print(f"Error: Could not open video file {video_path}")
        return
    
    fps = cap.get(cv2.CAP_PROP_FPS)
    detections = []
    frame_count = 0
    
    print("Processing video for person detection...")
    
    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break
        
        # Run YOLO detection
        results = model(frame, verbose=False)
        
        # Process results
        persons = []
        for result in results:
            boxes = result.boxes
            for box in boxes:
                # Check if detected object is a person (class 0 in COCO dataset)
                if int(box.cls) == 0:  # Person class
                    x1, y1, x2, y2 = box.xyxy[0].tolist()
                    confidence = float(box.conf[0])
                    
                    persons.append({
                        'bbox': [int(x1), int(y1), int(x2), int(y2)],
                        'confidence': round(confidence, 4)
                    })
        
        # Save detection for this frame
        if persons:
            detections.append({
                'frame': frame_count,
                'timestamp': round(frame_count / fps, 2),
                'persons': persons
            })
        
        # Display frame with detections
        annotated_frame = results[0].plot()
        cv2.imshow('Person Detection', annotated_frame)
        
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        
        frame_count += 1
    
    cap.release()
    cv2.destroyAllWindows()
    
    # Save detections to JSON
    output_data = {
        'video_id': os.path.basename(video_path),
        'total_frames': frame_count,
        'fps': fps,
        'detections': detections
    }
    
    with open(output_file, 'w') as f:
        json.dump(output_data, f, indent=2)
    
    print(f"Detection complete. Found persons in {len(detections)} frames.")
    print(f"Results saved to {output_file}")


def detect_persons_opencv(video_path, output_file='annotations/person_detections.json'):
    """
    Detect persons using OpenCV's HOG descriptor (alternative to YOLO).
    
    Args:
        video_path: Path to the input video file
        output_file: Path to save detection results
    """
    # Initialize HOG descriptor for person detection
    hog = cv2.HOGDescriptor()
    hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
    
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        print(f"Error: Could not open video file {video_path}")
        return
    
    fps = cap.get(cv2.CAP_PROP_FPS)
    detections = []
    frame_count = 0
    
    print("Processing video for person detection using OpenCV HOG...")
    
    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break
        
        # Detect persons
        boxes, weights = hog.detectMultiScale(frame, winStride=(8, 8), padding=(32, 32), scale=1.05)
        
        persons = []
        for (x, y, w, h), weight in zip(boxes, weights):
            if weight > 0.5:  # Confidence threshold
                persons.append({
                    'bbox': [int(x), int(y), int(x + w), int(y + h)],
                    'confidence': round(float(weight), 4)
                })
                
                # Draw bounding box
                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        
        if persons:
            detections.append({
                'frame': frame_count,
                'timestamp': round(frame_count / fps, 2),
                'persons': persons
            })
        
        cv2.imshow('Person Detection (OpenCV)', frame)
        
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        
        frame_count += 1
    
    cap.release()
    cv2.destroyAllWindows()
    
    # Save detections
    os.makedirs(os.path.dirname(output_file) if os.path.dirname(output_file) else '.', exist_ok=True)
    
    output_data = {
        'video_id': os.path.basename(video_path),
        'total_frames': frame_count,
        'fps': fps,
        'detections': detections
    }
    
    with open(output_file, 'w') as f:
        json.dump(output_data, f, indent=2)
    
    print(f"Detection complete. Found persons in {len(detections)} frames.")
    print(f"Results saved to {output_file}")


if __name__ == "__main__":
    video_path = "videos/sample.mp4"
    
    if os.path.exists(video_path):
        # Try YOLO first, fallback to OpenCV
        if YOLO_AVAILABLE:
            detect_persons_yolo(video_path)
        else:
            print("Using OpenCV HOG detector (YOLO not available)")
            detect_persons_opencv(video_path)
    else:
        print(f"Video file not found: {video_path}")
        print("Please place your video files in the 'videos' directory")

206 lines•6.3 KB
python

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer