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 8.3 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
  1. import argparse
  2. from collections import defaultdict
  3. from pathlib import Path
  4. import cv2
  5. import numpy as np
  6. from shapely.geometry import Polygon
  7. from shapely.geometry.point import Point
  8. from ultralytics import YOLO
  9. from ultralytics.utils.files import increment_path
  10. from ultralytics.utils.plotting import Annotator, colors
  11. track_history = defaultdict(list)
  12. current_region = None
  13. counting_regions = [
  14. {
  15. 'name': 'YOLOv8 Polygon Region',
  16. 'polygon': Polygon([(50, 80), (250, 20), (450, 80), (400, 350), (100, 350)]), # Polygon points
  17. 'counts': 0,
  18. 'dragging': False,
  19. 'region_color': (255, 42, 4), # BGR Value
  20. 'text_color': (255, 255, 255) # Region Text Color
  21. },
  22. {
  23. 'name': 'YOLOv8 Rectangle Region',
  24. 'polygon': Polygon([(200, 250), (440, 250), (440, 550), (200, 550)]), # Polygon points
  25. 'counts': 0,
  26. 'dragging': False,
  27. 'region_color': (37, 255, 225), # BGR Value
  28. 'text_color': (0, 0, 0), # Region Text Color
  29. }, ]
  30. def mouse_callback(event, x, y, flags, param):
  31. """Mouse call back event."""
  32. global current_region
  33. # Mouse left button down event
  34. if event == cv2.EVENT_LBUTTONDOWN:
  35. for region in counting_regions:
  36. if region['polygon'].contains(Point((x, y))):
  37. current_region = region
  38. current_region['dragging'] = True
  39. current_region['offset_x'] = x
  40. current_region['offset_y'] = y
  41. # Mouse move event
  42. elif event == cv2.EVENT_MOUSEMOVE:
  43. if current_region is not None and current_region['dragging']:
  44. dx = x - current_region['offset_x']
  45. dy = y - current_region['offset_y']
  46. current_region['polygon'] = Polygon([
  47. (p[0] + dx, p[1] + dy) for p in current_region['polygon'].exterior.coords])
  48. current_region['offset_x'] = x
  49. current_region['offset_y'] = y
  50. # Mouse left button up event
  51. elif event == cv2.EVENT_LBUTTONUP:
  52. if current_region is not None and current_region['dragging']:
  53. current_region['dragging'] = False
  54. def run(
  55. weights='yolov8n.pt',
  56. source=None,
  57. device='cpu',
  58. view_img=False,
  59. save_img=False,
  60. exist_ok=False,
  61. classes=None,
  62. line_thickness=2,
  63. track_thickness=2,
  64. region_thickness=2,
  65. ):
  66. """
  67. Run Region counting on a video using YOLOv8 and ByteTrack.
  68. Supports movable region for real time counting inside specific area.
  69. Supports multiple regions counting.
  70. Regions can be Polygons or rectangle in shape
  71. Args:
  72. weights (str): Model weights path.
  73. source (str): Video file path.
  74. device (str): processing device cpu, 0, 1
  75. view_img (bool): Show results.
  76. save_img (bool): Save results.
  77. exist_ok (bool): Overwrite existing files.
  78. classes (list): classes to detect and track
  79. line_thickness (int): Bounding box thickness.
  80. track_thickness (int): Tracking line thickness
  81. region_thickness (int): Region thickness.
  82. """
  83. vid_frame_count = 0
  84. # Check source path
  85. if not Path(source).exists():
  86. raise FileNotFoundError(f"Source path '{source}' does not exist.")
  87. # Setup Model
  88. model = YOLO(f'{weights}')
  89. model.to('cuda') if device == '0' else model.to('cpu')
  90. # Extract classes names
  91. names = model.model.names
  92. # Video setup
  93. videocapture = cv2.VideoCapture(source)
  94. frame_width, frame_height = int(videocapture.get(3)), int(videocapture.get(4))
  95. fps, fourcc = int(videocapture.get(5)), cv2.VideoWriter_fourcc(*'mp4v')
  96. # Output setup
  97. save_dir = increment_path(Path('ultralytics_rc_output') / 'exp', exist_ok)
  98. save_dir.mkdir(parents=True, exist_ok=True)
  99. video_writer = cv2.VideoWriter(str(save_dir / f'{Path(source).stem}.mp4'), fourcc, fps, (frame_width, frame_height))
  100. # Iterate over video frames
  101. while videocapture.isOpened():
  102. success, frame = videocapture.read()
  103. if not success:
  104. break
  105. vid_frame_count += 1
  106. # Extract the results
  107. results = model.track(frame, persist=True, classes=classes)
  108. if results[0].boxes.id is not None:
  109. boxes = results[0].boxes.xyxy.cpu()
  110. track_ids = results[0].boxes.id.int().cpu().tolist()
  111. clss = results[0].boxes.cls.cpu().tolist()
  112. annotator = Annotator(frame, line_width=line_thickness, example=str(names))
  113. for box, track_id, cls in zip(boxes, track_ids, clss):
  114. annotator.box_label(box, str(names[cls]), color=colors(cls, True))
  115. bbox_center = (box[0] + box[2]) / 2, (box[1] + box[3]) / 2 # Bbox center
  116. track = track_history[track_id] # Tracking Lines plot
  117. track.append((float(bbox_center[0]), float(bbox_center[1])))
  118. if len(track) > 30:
  119. track.pop(0)
  120. points = np.hstack(track).astype(np.int32).reshape((-1, 1, 2))
  121. cv2.polylines(frame, [points], isClosed=False, color=colors(cls, True), thickness=track_thickness)
  122. # Check if detection inside region
  123. for region in counting_regions:
  124. if region['polygon'].contains(Point((bbox_center[0], bbox_center[1]))):
  125. region['counts'] += 1
  126. # Draw regions (Polygons/Rectangles)
  127. for region in counting_regions:
  128. region_label = str(region['counts'])
  129. region_color = region['region_color']
  130. region_text_color = region['text_color']
  131. polygon_coords = np.array(region['polygon'].exterior.coords, dtype=np.int32)
  132. centroid_x, centroid_y = int(region['polygon'].centroid.x), int(region['polygon'].centroid.y)
  133. text_size, _ = cv2.getTextSize(region_label,
  134. cv2.FONT_HERSHEY_SIMPLEX,
  135. fontScale=0.7,
  136. thickness=line_thickness)
  137. text_x = centroid_x - text_size[0] // 2
  138. text_y = centroid_y + text_size[1] // 2
  139. cv2.rectangle(frame, (text_x - 5, text_y - text_size[1] - 5), (text_x + text_size[0] + 5, text_y + 5),
  140. region_color, -1)
  141. cv2.putText(frame, region_label, (text_x, text_y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, region_text_color,
  142. line_thickness)
  143. cv2.polylines(frame, [polygon_coords], isClosed=True, color=region_color, thickness=region_thickness)
  144. if view_img:
  145. if vid_frame_count == 1:
  146. cv2.namedWindow('Ultralytics YOLOv8 Region Counter Movable')
  147. cv2.setMouseCallback('Ultralytics YOLOv8 Region Counter Movable', mouse_callback)
  148. cv2.imshow('Ultralytics YOLOv8 Region Counter Movable', frame)
  149. if save_img:
  150. video_writer.write(frame)
  151. for region in counting_regions: # Reinitialize count for each region
  152. region['counts'] = 0
  153. if cv2.waitKey(1) & 0xFF == ord('q'):
  154. break
  155. del vid_frame_count
  156. video_writer.release()
  157. videocapture.release()
  158. cv2.destroyAllWindows()
  159. def parse_opt():
  160. """Parse command line arguments."""
  161. parser = argparse.ArgumentParser()
  162. parser.add_argument('--weights', type=str, default='yolov8n.pt', help='initial weights path')
  163. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  164. parser.add_argument('--source', type=str, required=True, help='video file path')
  165. parser.add_argument('--view-img', action='store_true', help='show results')
  166. parser.add_argument('--save-img', action='store_true', help='save results')
  167. parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
  168. parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
  169. parser.add_argument('--line-thickness', type=int, default=2, help='bounding box thickness')
  170. parser.add_argument('--track-thickness', type=int, default=2, help='Tracking line thickness')
  171. parser.add_argument('--region-thickness', type=int, default=4, help='Region thickness')
  172. return parser.parse_args()
  173. def main(opt):
  174. """Main function."""
  175. run(**vars(opt))
  176. if __name__ == '__main__':
  177. opt = parse_opt()
  178. main(opt)
Tip!

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

Comments

Loading...