Update objec_detect_yolo.py
Browse files- objec_detect_yolo.py +41 -61
objec_detect_yolo.py
CHANGED
@@ -5,117 +5,97 @@ from ultralytics import YOLO
|
|
5 |
import time
|
6 |
from typing import Tuple, Set
|
7 |
|
8 |
-
def
|
9 |
"""
|
10 |
-
Detects and tracks objects in a video using YOLOv8 model, saving an annotated output video.
|
11 |
-
|
12 |
Args:
|
13 |
-
path (str): Path to the input video file.
|
14 |
-
|
15 |
Returns:
|
16 |
Tuple[Set[str], str]:
|
17 |
- Set of unique detected object labels (e.g., {'Gun', 'Knife'})
|
18 |
- Path to the output annotated video with detection boxes and tracking IDs
|
19 |
-
|
20 |
-
Raises:
|
21 |
-
FileNotFoundError: If input video doesn't exist
|
22 |
-
ValueError: If video cannot be opened/processed
|
23 |
"""
|
24 |
-
|
25 |
-
# Validate input file exists
|
26 |
if not os.path.exists(path):
|
27 |
raise FileNotFoundError(f"Video file not found: {path}")
|
28 |
|
29 |
-
#
|
30 |
-
|
31 |
-
|
32 |
-
class_names = model.names # Get class label mappings
|
33 |
|
34 |
-
#
|
35 |
-
# 1. Temporary output during processing
|
36 |
-
# 2. Final output with detected objects in filename
|
37 |
input_video_name = os.path.basename(path)
|
38 |
base_name = os.path.splitext(input_video_name)[0]
|
39 |
temp_output_name = f"{base_name}_output_temp.mp4"
|
40 |
output_dir = "results"
|
41 |
-
os.makedirs(output_dir, exist_ok=True)
|
42 |
-
if not os.path.exists(output_dir):
|
43 |
-
raise ValueError(f"Failed to create output directory: {output_dir}")
|
44 |
temp_output_path = os.path.join(output_dir, temp_output_name)
|
45 |
|
46 |
-
# Video
|
47 |
-
# - Open input video stream
|
48 |
-
# - Initialize output writer with MP4 codec
|
49 |
cap = cv2.VideoCapture(path)
|
50 |
if not cap.isOpened():
|
51 |
raise ValueError(f"Failed to open video file: {path}")
|
52 |
|
53 |
-
# Process all frames at 640x640 resolution for consistency
|
54 |
frame_width, frame_height = 640, 640
|
55 |
out = cv2.VideoWriter(
|
56 |
-
temp_output_path,
|
57 |
-
cv2.VideoWriter_fourcc(*'mp4v'),
|
58 |
-
30.0,
|
59 |
(frame_width, frame_height)
|
60 |
)
|
61 |
|
62 |
-
|
63 |
-
# 1. Read each frame
|
64 |
-
# 2. Run object detection + tracking
|
65 |
-
# 3. Annotate frame with boxes and IDs
|
66 |
-
# 4. Collect detected classes
|
67 |
-
crimes = [] # Track all detected objects
|
68 |
start = time.time()
|
69 |
print(f"[INFO] Processing started at {start:.2f} seconds")
|
70 |
|
71 |
while True:
|
72 |
ret, frame = cap.read()
|
73 |
-
if not ret:
|
74 |
break
|
75 |
|
76 |
-
# Resize and run detection + tracking
|
77 |
frame = cv2.resize(frame, (frame_width, frame_height))
|
|
|
|
|
78 |
results = model.track(
|
79 |
source=frame,
|
80 |
-
conf=0.7,
|
81 |
-
persist=True
|
82 |
)
|
83 |
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
# Record detected classes
|
88 |
-
for box in results[0].boxes:
|
89 |
-
cls = int(box.cls)
|
90 |
-
crimes.append(class_names[cls])
|
91 |
|
92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
93 |
|
94 |
-
# Clean up video resources
|
95 |
end = time.time()
|
96 |
-
print(f"[INFO] Processing finished at {end:.2f} seconds")
|
97 |
-
print(f"[INFO] Total execution time: {end - start:.2f} seconds")
|
98 |
cap.release()
|
99 |
out.release()
|
100 |
|
101 |
-
#
|
102 |
-
|
103 |
-
unique_crimes = set(crimes)
|
104 |
-
crimes_str = "_".join(sorted(unique_crimes)).replace(" ", "_")[:50] # truncate if needed
|
105 |
final_output_name = f"{base_name}_{crimes_str}_output.mp4"
|
106 |
final_output_path = os.path.join(output_dir, final_output_name)
|
107 |
|
108 |
-
# Rename the video file
|
109 |
os.rename(temp_output_path, final_output_path)
|
110 |
|
111 |
-
print(f"[INFO]
|
|
|
|
|
112 |
print(f"[INFO] Annotated video saved at: {final_output_path}")
|
113 |
|
114 |
-
return
|
115 |
|
116 |
|
117 |
-
#
|
118 |
-
#
|
119 |
-
#
|
120 |
-
#
|
121 |
-
#
|
|
|
5 |
import time
|
6 |
from typing import Tuple, Set
|
7 |
|
8 |
+
def detect_objects_in_video(path: str) -> Tuple[Set[str], str]:
|
9 |
"""
|
10 |
+
Detects and tracks objects in a video using a YOLOv8 model, saving an annotated output video.
|
11 |
+
|
12 |
Args:
|
13 |
+
path (str): Path to the input video file.
|
14 |
+
|
15 |
Returns:
|
16 |
Tuple[Set[str], str]:
|
17 |
- Set of unique detected object labels (e.g., {'Gun', 'Knife'})
|
18 |
- Path to the output annotated video with detection boxes and tracking IDs
|
|
|
|
|
|
|
|
|
19 |
"""
|
|
|
|
|
20 |
if not os.path.exists(path):
|
21 |
raise FileNotFoundError(f"Video file not found: {path}")
|
22 |
|
23 |
+
# Load YOLOv8 model (adjust path if necessary)
|
24 |
+
model = YOLO("yolo/best.pt") # Make sure this path is correct
|
25 |
+
class_names = model.names
|
|
|
26 |
|
27 |
+
# Output setup
|
|
|
|
|
28 |
input_video_name = os.path.basename(path)
|
29 |
base_name = os.path.splitext(input_video_name)[0]
|
30 |
temp_output_name = f"{base_name}_output_temp.mp4"
|
31 |
output_dir = "results"
|
32 |
+
os.makedirs(output_dir, exist_ok=True)
|
|
|
|
|
33 |
temp_output_path = os.path.join(output_dir, temp_output_name)
|
34 |
|
35 |
+
# Video I/O setup
|
|
|
|
|
36 |
cap = cv2.VideoCapture(path)
|
37 |
if not cap.isOpened():
|
38 |
raise ValueError(f"Failed to open video file: {path}")
|
39 |
|
|
|
40 |
frame_width, frame_height = 640, 640
|
41 |
out = cv2.VideoWriter(
|
42 |
+
temp_output_path,
|
43 |
+
cv2.VideoWriter_fourcc(*'mp4v'),
|
44 |
+
30.0,
|
45 |
(frame_width, frame_height)
|
46 |
)
|
47 |
|
48 |
+
detected_labels = set()
|
|
|
|
|
|
|
|
|
|
|
49 |
start = time.time()
|
50 |
print(f"[INFO] Processing started at {start:.2f} seconds")
|
51 |
|
52 |
while True:
|
53 |
ret, frame = cap.read()
|
54 |
+
if not ret:
|
55 |
break
|
56 |
|
|
|
57 |
frame = cv2.resize(frame, (frame_width, frame_height))
|
58 |
+
|
59 |
+
# Run detection and tracking
|
60 |
results = model.track(
|
61 |
source=frame,
|
62 |
+
conf=0.7,
|
63 |
+
persist=True
|
64 |
)
|
65 |
|
66 |
+
if results and hasattr(results[0], "plot"):
|
67 |
+
annotated_frame = results[0].plot()
|
68 |
+
out.write(annotated_frame)
|
|
|
|
|
|
|
|
|
69 |
|
70 |
+
# Extract class labels
|
71 |
+
if hasattr(results[0], "boxes"):
|
72 |
+
for box in results[0].boxes:
|
73 |
+
cls = int(box.cls)
|
74 |
+
detected_labels.add(class_names[cls])
|
75 |
+
else:
|
76 |
+
out.write(frame)
|
77 |
|
|
|
78 |
end = time.time()
|
|
|
|
|
79 |
cap.release()
|
80 |
out.release()
|
81 |
|
82 |
+
# Create final output filename
|
83 |
+
crimes_str = "_".join(sorted(detected_labels)).replace(" ", "_")[:50]
|
|
|
|
|
84 |
final_output_name = f"{base_name}_{crimes_str}_output.mp4"
|
85 |
final_output_path = os.path.join(output_dir, final_output_name)
|
86 |
|
|
|
87 |
os.rename(temp_output_path, final_output_path)
|
88 |
|
89 |
+
print(f"[INFO] Processing finished at {end:.2f} seconds")
|
90 |
+
print(f"[INFO] Total execution time: {end - start:.2f} seconds")
|
91 |
+
print(f"[INFO] Detected crimes: {detected_labels}")
|
92 |
print(f"[INFO] Annotated video saved at: {final_output_path}")
|
93 |
|
94 |
+
return detected_labels, final_output_path
|
95 |
|
96 |
|
97 |
+
# Example usage (uncomment to use as standalone script)
|
98 |
+
# if __name__ == "__main__":
|
99 |
+
# video_path = input("Enter the path to the video file: ").strip('"')
|
100 |
+
# print(f"[INFO] Loading video: {video_path}")
|
101 |
+
# detect_objects_in_video(video_path)
|