KillD00zer commited on
Commit
6b881e8
·
verified ·
1 Parent(s): 5ae5094

Update objec_detect_yolo.py

Browse files
Files changed (1) hide show
  1. objec_detect_yolo.py +121 -121
objec_detect_yolo.py CHANGED
@@ -1,121 +1,121 @@
1
- import cv2
2
- import numpy as np
3
- import os
4
- from ultralytics import YOLO
5
- import time
6
- from typing import Tuple, Set
7
-
8
- def detection(path: str) -> Tuple[Set[str], str]:
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. Supports common video formats (mp4, avi, etc.)
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
- # Initialize YOLOv8 model with pretrained weights
30
- # Model is trained to detect: ['Fire', 'Gun', 'License_Plate', 'Smoke', 'knife']
31
- model = YOLO(os.path.join(os.path.dirname(__file__), "yolo", "best.pt"))
32
- class_names = model.names # Get class label mappings
33
-
34
- # Set up output paths:
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) # Create output dir if needed
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 processing setup:
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'), # MP4 codec
58
- 30.0, # Output FPS
59
- (frame_width, frame_height)
60
- )
61
-
62
- # Main processing loop:
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: # End of video
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, # Minimum confidence threshold
81
- persist=True # Enable tracking across frames
82
- )
83
-
84
- # Annotate frame with boxes and tracking IDs
85
- annotated_frame = results[0].plot()
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
- out.write(annotated_frame)
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
- # Generate final output filename containing detected object labels
102
- # Format: {original_name}_{detected_objects}_output.mp4
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] Detected crimes: {unique_crimes}")
112
- print(f"[INFO] Annotated video saved at: {final_output_path}")
113
-
114
- return unique_crimes, final_output_path
115
-
116
-
117
- # # Entry point
118
- # path0 = input("Enter the local path to the video file to detect objects: ")
119
- # path = path0.strip('"') # Remove extra quotes if copied from Windows
120
- # print(f"[INFO] Loading video: {path}")
121
- # detection(path)
 
1
+ import cv2
2
+ import numpy as np
3
+ import os
4
+ from ultralytics import YOLO
5
+ import time
6
+ from typing import Tuple, Set
7
+
8
+ def detection(path: str) -> Tuple[Set[str], str]:
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. Supports common video formats (mp4, avi, etc.)
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
+ # Initialize YOLOv8 model with pretrained weights
30
+ # Model is trained to detect: ['Fire', 'Gun', 'License_Plate', 'Smoke', 'knife']
31
+ model = YOLO("yolo", "best.pt"))
32
+ class_names = model.names # Get class label mappings
33
+
34
+ # Set up output paths:
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) # Create output dir if needed
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 processing setup:
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'), # MP4 codec
58
+ 30.0, # Output FPS
59
+ (frame_width, frame_height)
60
+ )
61
+
62
+ # Main processing loop:
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: # End of video
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, # Minimum confidence threshold
81
+ persist=True # Enable tracking across frames
82
+ )
83
+
84
+ # Annotate frame with boxes and tracking IDs
85
+ annotated_frame = results[0].plot()
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
+ out.write(annotated_frame)
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
+ # Generate final output filename containing detected object labels
102
+ # Format: {original_name}_{detected_objects}_output.mp4
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] Detected crimes: {unique_crimes}")
112
+ print(f"[INFO] Annotated video saved at: {final_output_path}")
113
+
114
+ return unique_crimes, final_output_path
115
+
116
+
117
+ # # Entry point
118
+ # path0 = input("Enter the local path to the video file to detect objects: ")
119
+ # path = path0.strip('"') # Remove extra quotes if copied from Windows
120
+ # print(f"[INFO] Loading video: {path}")
121
+ # detection(path)