The model was trained on a custom threat detection dataset, meticulously curated and annotated for robust performance across various scenarios.
1# process video in batches
2import cv2
3from ultralytics import YOLO
4from huggingface_hub import hf_hub_download
5import torch
6from tqdm import tqdm
7
8# Configuration
9MODEL_REPO = "Subh775/Threat-Detection-YOLOv8n"
10INPUT_VIDEO = "input_video.mp4"
11OUTPUT_VIDEO = "output_video.mp4"
12CONFIDENCE_THRESHOLD = 0.4
13BATCH_SIZE = 32 # Adjust based on GPU memory
14
15# Setup device
16device = 0 if torch.cuda.is_available() else "cpu"
17print(f"Using device: {'GPU' if device == 0 else 'CPU'}")
18
19# Load model
20model_path = hf_hub_download(repo_id=MODEL_REPO, filename="weights/best.pt")
21model = YOLO(model_path)
22
23# Process video
24cap = cv2.VideoCapture(INPUT_VIDEO)
25frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
26frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
27fps = int(cap.get(cv2.CAP_PROP_FPS))
28total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
29
30fourcc = cv2.VideoWriter_fourcc(*'mp4v')
31out = cv2.VideoWriter(OUTPUT_VIDEO, fourcc, fps, (frame_width, frame_height))
32
33frames_batch = []
34with tqdm(total=total_frames, desc="Processing video") as pbar:
35 while cap.isOpened():
36 success, frame = cap.read()
37 if success:
38 frames_batch.append(frame)
39
40 if len(frames_batch) == BATCH_SIZE:
41 # Batch inference
42 results = model(frames_batch, conf=CONFIDENCE_THRESHOLD,
43 device=device, verbose=False)
44
45 # Write annotated frames
46 for result in results:
47 annotated_frame = result.plot()
48 out.write(annotated_frame)
49
50 pbar.update(len(frames_batch))
51 frames_batch = []
52 else:
53 break
54
55# Process remaining frames
56if frames_batch:
57 results = model(frames_batch, conf=CONFIDENCE_THRESHOLD,
58 device=device, verbose=False)
59 for result in results:
60 annotated_frame = result.plot()
61 out.write(annotated_frame)
62 pbar.update(len(frames_batch))
63
64cap.release()
65out.release()
66print(f"Processed video saved to: {OUTPUT_VIDEO}")
67