Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

yolov8_region_counter.py 10.0 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. import argparse
  3. from collections import defaultdict
  4. from pathlib import Path
  5. from typing import Any, List
  6. import cv2
  7. import numpy as np
  8. from shapely.geometry import Polygon
  9. from shapely.geometry.point import Point
  10. from ultralytics import YOLO
  11. from ultralytics.utils.files import increment_path
  12. from ultralytics.utils.plotting import Annotator, colors
  13. track_history = defaultdict(list)
  14. current_region = None
  15. counting_regions = [
  16. {
  17. "name": "Ultralytics YOLO Polygon Region",
  18. "polygon": Polygon([(50, 80), (250, 20), (450, 80), (400, 350), (100, 350)]), # Polygon points
  19. "counts": 0,
  20. "dragging": False,
  21. "region_color": (255, 42, 4), # BGR Value
  22. "text_color": (255, 255, 255), # Region Text Color
  23. },
  24. {
  25. "name": "Ultralytics YOLO Rectangle Region",
  26. "polygon": Polygon([(200, 250), (440, 250), (440, 550), (200, 550)]), # Polygon points
  27. "counts": 0,
  28. "dragging": False,
  29. "region_color": (37, 255, 225), # BGR Value
  30. "text_color": (0, 0, 0), # Region Text Color
  31. },
  32. ]
  33. def mouse_callback(event: int, x: int, y: int, flags: int, param: Any) -> None:
  34. """
  35. Handle mouse events for region manipulation in the video frame.
  36. This function enables interactive region selection and dragging functionality for counting regions. It responds to
  37. mouse button down, move, and up events to allow users to select and reposition counting regions in real-time.
  38. Args:
  39. event (int): The mouse event type (e.g., cv2.EVENT_LBUTTONDOWN, cv2.EVENT_MOUSEMOVE).
  40. x (int): The x-coordinate of the mouse pointer.
  41. y (int): The y-coordinate of the mouse pointer.
  42. flags (int): Additional flags passed by OpenCV.
  43. param (Any): Additional parameters passed to the callback.
  44. Examples:
  45. Set up mouse callback for interactive region manipulation
  46. >>> cv2.setMouseCallback("window_name", mouse_callback)
  47. """
  48. global current_region
  49. # Mouse left button down event
  50. if event == cv2.EVENT_LBUTTONDOWN:
  51. for region in counting_regions:
  52. if region["polygon"].contains(Point((x, y))):
  53. current_region = region
  54. current_region["dragging"] = True
  55. current_region["offset_x"] = x
  56. current_region["offset_y"] = y
  57. # Mouse move event
  58. elif event == cv2.EVENT_MOUSEMOVE:
  59. if current_region is not None and current_region["dragging"]:
  60. dx = x - current_region["offset_x"]
  61. dy = y - current_region["offset_y"]
  62. current_region["polygon"] = Polygon(
  63. [(p[0] + dx, p[1] + dy) for p in current_region["polygon"].exterior.coords]
  64. )
  65. current_region["offset_x"] = x
  66. current_region["offset_y"] = y
  67. # Mouse left button up event
  68. elif event == cv2.EVENT_LBUTTONUP:
  69. if current_region is not None and current_region["dragging"]:
  70. current_region["dragging"] = False
  71. def run(
  72. weights: str = "yolo11n.pt",
  73. source: str = None,
  74. device: str = "cpu",
  75. view_img: bool = False,
  76. save_img: bool = False,
  77. exist_ok: bool = False,
  78. classes: List[int] = None,
  79. line_thickness: int = 2,
  80. track_thickness: int = 2,
  81. region_thickness: int = 2,
  82. ) -> None:
  83. """
  84. Run object detection and counting within specified regions using YOLO and ByteTrack.
  85. This function performs real-time object detection, tracking, and counting within user-defined polygonal or
  86. rectangular regions. It supports interactive region manipulation, multiple counting areas, and both live viewing
  87. and video saving capabilities.
  88. Args:
  89. weights (str): Path to the YOLO model weights file.
  90. source (str): Path to the input video file.
  91. device (str): Processing device specification ('cpu', '0', '1', etc.).
  92. view_img (bool): Display results in a live window.
  93. save_img (bool): Save processed video to file.
  94. exist_ok (bool): Overwrite existing output files without incrementing.
  95. classes (List[int], optional): Specific class IDs to detect and track.
  96. line_thickness (int): Thickness of bounding box lines.
  97. track_thickness (int): Thickness of object tracking lines.
  98. region_thickness (int): Thickness of counting region boundaries.
  99. Examples:
  100. Run region counting with default settings
  101. >>> run(source="video.mp4", view_img=True)
  102. Run with custom model and specific classes
  103. >>> run(weights="yolo11s.pt", source="traffic.mp4", classes=[0, 2, 3], device="0")
  104. """
  105. vid_frame_count = 0
  106. # Check source path
  107. if not Path(source).exists():
  108. raise FileNotFoundError(f"Source path '{source}' does not exist.")
  109. # Setup Model
  110. model = YOLO(f"{weights}")
  111. model.to("cuda") if device == "0" else model.to("cpu")
  112. # Extract classes names
  113. names = model.names
  114. # Video setup
  115. videocapture = cv2.VideoCapture(source)
  116. frame_width = int(videocapture.get(3))
  117. frame_height = int(videocapture.get(4))
  118. fps = int(videocapture.get(5))
  119. fourcc = cv2.VideoWriter_fourcc(*"mp4v")
  120. # Output setup
  121. save_dir = increment_path(Path("ultralytics_rc_output") / "exp", exist_ok)
  122. save_dir.mkdir(parents=True, exist_ok=True)
  123. video_writer = cv2.VideoWriter(str(save_dir / f"{Path(source).stem}.avi"), fourcc, fps, (frame_width, frame_height))
  124. # Iterate over video frames
  125. while videocapture.isOpened():
  126. success, frame = videocapture.read()
  127. if not success:
  128. break
  129. vid_frame_count += 1
  130. # Extract the results
  131. results = model.track(frame, persist=True, classes=classes)
  132. if results[0].boxes.is_track:
  133. boxes = results[0].boxes.xyxy.cpu()
  134. track_ids = results[0].boxes.id.int().cpu().tolist()
  135. clss = results[0].boxes.cls.cpu().tolist()
  136. annotator = Annotator(frame, line_width=line_thickness, example=str(names))
  137. for box, track_id, cls in zip(boxes, track_ids, clss):
  138. annotator.box_label(box, str(names[cls]), color=colors(cls, True))
  139. bbox_center = (box[0] + box[2]) / 2, (box[1] + box[3]) / 2 # Bbox center
  140. track = track_history[track_id] # Tracking Lines plot
  141. track.append((float(bbox_center[0]), float(bbox_center[1])))
  142. if len(track) > 30:
  143. track.pop(0)
  144. points = np.hstack(track).astype(np.int32).reshape((-1, 1, 2))
  145. cv2.polylines(frame, [points], isClosed=False, color=colors(cls, True), thickness=track_thickness)
  146. # Check if detection inside region
  147. for region in counting_regions:
  148. if region["polygon"].contains(Point((bbox_center[0], bbox_center[1]))):
  149. region["counts"] += 1
  150. # Draw regions (Polygons/Rectangles)
  151. for region in counting_regions:
  152. region_label = str(region["counts"])
  153. region_color = region["region_color"]
  154. region_text_color = region["text_color"]
  155. polygon_coordinates = np.array(region["polygon"].exterior.coords, dtype=np.int32)
  156. centroid_x, centroid_y = int(region["polygon"].centroid.x), int(region["polygon"].centroid.y)
  157. text_size, _ = cv2.getTextSize(
  158. region_label, cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.7, thickness=line_thickness
  159. )
  160. text_x = centroid_x - text_size[0] // 2
  161. text_y = centroid_y + text_size[1] // 2
  162. cv2.rectangle(
  163. frame,
  164. (text_x - 5, text_y - text_size[1] - 5),
  165. (text_x + text_size[0] + 5, text_y + 5),
  166. region_color,
  167. -1,
  168. )
  169. cv2.putText(
  170. frame, region_label, (text_x, text_y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, region_text_color, line_thickness
  171. )
  172. cv2.polylines(frame, [polygon_coordinates], isClosed=True, color=region_color, thickness=region_thickness)
  173. if view_img:
  174. if vid_frame_count == 1:
  175. cv2.namedWindow("Ultralytics YOLO Region Counter Movable")
  176. cv2.setMouseCallback("Ultralytics YOLO Region Counter Movable", mouse_callback)
  177. cv2.imshow("Ultralytics YOLO Region Counter Movable", frame)
  178. if save_img:
  179. video_writer.write(frame)
  180. for region in counting_regions: # Reinitialize count for each region
  181. region["counts"] = 0
  182. if cv2.waitKey(1) & 0xFF == ord("q"):
  183. break
  184. del vid_frame_count
  185. video_writer.release()
  186. videocapture.release()
  187. cv2.destroyAllWindows()
  188. def parse_opt() -> argparse.Namespace:
  189. """Parse command line arguments for the region counting application."""
  190. parser = argparse.ArgumentParser()
  191. parser.add_argument("--weights", type=str, default="yolo11n.pt", help="initial weights path")
  192. parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
  193. parser.add_argument("--source", type=str, required=True, help="video file path")
  194. parser.add_argument("--view-img", action="store_true", help="show results")
  195. parser.add_argument("--save-img", action="store_true", help="save results")
  196. parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment")
  197. parser.add_argument("--classes", nargs="+", type=int, help="filter by class: --classes 0, or --classes 0 2 3")
  198. parser.add_argument("--line-thickness", type=int, default=2, help="bounding box thickness")
  199. parser.add_argument("--track-thickness", type=int, default=2, help="Tracking line thickness")
  200. parser.add_argument("--region-thickness", type=int, default=4, help="Region thickness")
  201. return parser.parse_args()
  202. def main(options: argparse.Namespace) -> None:
  203. """Execute the main region counting functionality with the provided options."""
  204. run(**vars(options))
  205. if __name__ == "__main__":
  206. opt = parse_opt()
  207. main(opt)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...