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

test_solutions.py 13 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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. # Tests Ultralytics Solutions: https://docs.ultralytics.com/solutions/,
  3. # including every solution excluding DistanceCalculation and Security Alarm System.
  4. import os
  5. from unittest.mock import patch
  6. import cv2
  7. import numpy as np
  8. import pytest
  9. from tests import MODEL, TMP
  10. from ultralytics import solutions
  11. from ultralytics.utils import ASSETS_URL, IS_RASPBERRYPI, checks
  12. from ultralytics.utils.downloads import safe_download
  13. # Pre-defined arguments values
  14. SHOW = False
  15. DEMO_VIDEO = "solutions_ci_demo.mp4" # for all the solutions, except workout, object cropping and parking management
  16. CROP_VIDEO = "decelera_landscape_min.mov" # for object cropping solution
  17. POSE_VIDEO = "solution_ci_pose_demo.mp4" # only for workouts monitoring solution
  18. PARKING_VIDEO = "solution_ci_parking_demo.mp4" # only for parking management solution
  19. PARKING_AREAS_JSON = "solution_ci_parking_areas.json" # only for parking management solution
  20. PARKING_MODEL = "solutions_ci_parking_model.pt" # only for parking management solution
  21. VERTICAL_VIDEO = "solution_vertical_demo.mp4" # only for vertical line counting
  22. REGION = [(10, 200), (540, 200), (540, 180), (10, 180)] # for object counting, speed estimation and queue management
  23. HORIZONTAL_LINE = [(10, 200), (540, 200)] # for object counting
  24. VERTICAL_LINE = [(320, 0), (320, 400)] # for object counting
  25. # Test configs for each solution : (name, class, needs_frame_count, video, kwargs)
  26. SOLUTIONS = [
  27. (
  28. "ObjectCounter",
  29. solutions.ObjectCounter,
  30. False,
  31. DEMO_VIDEO,
  32. {"region": REGION, "model": MODEL, "show": SHOW},
  33. ),
  34. (
  35. "ObjectCounter",
  36. solutions.ObjectCounter,
  37. False,
  38. DEMO_VIDEO,
  39. {"region": HORIZONTAL_LINE, "model": MODEL, "show": SHOW},
  40. ),
  41. (
  42. "ObjectCounterVertical",
  43. solutions.ObjectCounter,
  44. False,
  45. DEMO_VIDEO,
  46. {"region": VERTICAL_LINE, "model": MODEL, "show": SHOW},
  47. ),
  48. (
  49. "ObjectCounterwithOBB",
  50. solutions.ObjectCounter,
  51. False,
  52. DEMO_VIDEO,
  53. {"region": REGION, "model": "yolo11n-obb.pt", "show": SHOW},
  54. ),
  55. (
  56. "Heatmap",
  57. solutions.Heatmap,
  58. False,
  59. DEMO_VIDEO,
  60. {"colormap": cv2.COLORMAP_PARULA, "model": MODEL, "show": SHOW, "region": None},
  61. ),
  62. (
  63. "HeatmapWithRegion",
  64. solutions.Heatmap,
  65. False,
  66. DEMO_VIDEO,
  67. {"colormap": cv2.COLORMAP_PARULA, "region": REGION, "model": MODEL, "show": SHOW},
  68. ),
  69. (
  70. "SpeedEstimator",
  71. solutions.SpeedEstimator,
  72. False,
  73. DEMO_VIDEO,
  74. {"region": REGION, "model": MODEL, "show": SHOW},
  75. ),
  76. (
  77. "QueueManager",
  78. solutions.QueueManager,
  79. False,
  80. DEMO_VIDEO,
  81. {"region": REGION, "model": MODEL, "show": SHOW},
  82. ),
  83. (
  84. "LineAnalytics",
  85. solutions.Analytics,
  86. True,
  87. DEMO_VIDEO,
  88. {"analytics_type": "line", "model": MODEL, "show": SHOW, "figsize": (6.4, 3.2)},
  89. ),
  90. (
  91. "PieAnalytics",
  92. solutions.Analytics,
  93. True,
  94. DEMO_VIDEO,
  95. {"analytics_type": "pie", "model": MODEL, "show": SHOW, "figsize": (6.4, 3.2)},
  96. ),
  97. (
  98. "BarAnalytics",
  99. solutions.Analytics,
  100. True,
  101. DEMO_VIDEO,
  102. {"analytics_type": "bar", "model": MODEL, "show": SHOW, "figsize": (6.4, 3.2)},
  103. ),
  104. (
  105. "AreaAnalytics",
  106. solutions.Analytics,
  107. True,
  108. DEMO_VIDEO,
  109. {"analytics_type": "area", "model": MODEL, "show": SHOW, "figsize": (6.4, 3.2)},
  110. ),
  111. ("TrackZone", solutions.TrackZone, False, DEMO_VIDEO, {"region": REGION, "model": MODEL, "show": SHOW}),
  112. (
  113. "ObjectCropper",
  114. solutions.ObjectCropper,
  115. False,
  116. CROP_VIDEO,
  117. {"crop_dir": str(TMP / "cropped-detections"), "model": MODEL, "show": SHOW},
  118. ),
  119. (
  120. "ObjectBlurrer",
  121. solutions.ObjectBlurrer,
  122. False,
  123. DEMO_VIDEO,
  124. {"blur_ratio": 0.02, "model": MODEL, "show": SHOW},
  125. ),
  126. (
  127. "InstanceSegmentation",
  128. solutions.InstanceSegmentation,
  129. False,
  130. DEMO_VIDEO,
  131. {"model": "yolo11n-seg.pt", "show": SHOW},
  132. ),
  133. ("VisionEye", solutions.VisionEye, False, DEMO_VIDEO, {"model": MODEL, "show": SHOW}),
  134. (
  135. "RegionCounter",
  136. solutions.RegionCounter,
  137. False,
  138. DEMO_VIDEO,
  139. {"region": REGION, "model": MODEL, "show": SHOW},
  140. ),
  141. ("AIGym", solutions.AIGym, False, POSE_VIDEO, {"kpts": [6, 8, 10], "show": SHOW}),
  142. (
  143. "ParkingManager",
  144. solutions.ParkingManagement,
  145. False,
  146. PARKING_VIDEO,
  147. {"model": str(TMP / PARKING_MODEL), "show": SHOW, "json_file": str(TMP / PARKING_AREAS_JSON)},
  148. ),
  149. (
  150. "StreamlitInference",
  151. solutions.Inference,
  152. False,
  153. None, # streamlit application doesn't require video file
  154. {}, # streamlit application doesn't accept arguments
  155. ),
  156. ]
  157. def process_video(solution, video_path: str, needs_frame_count: bool = False):
  158. """Process video with solution, feeding frames and optional frame count to the solution instance."""
  159. cap = cv2.VideoCapture(video_path)
  160. assert cap.isOpened(), f"Error reading video file {video_path}"
  161. frame_count = 0
  162. while cap.isOpened():
  163. success, im0 = cap.read()
  164. if not success:
  165. break
  166. frame_count += 1
  167. im_copy = im0.copy()
  168. args = [im_copy, frame_count] if needs_frame_count else [im_copy]
  169. _ = solution(*args)
  170. cap.release()
  171. @pytest.mark.skipif(IS_RASPBERRYPI, reason="Disabled for testing due to --slow test errors after YOLOE PR.")
  172. @pytest.mark.parametrize("name, solution_class, needs_frame_count, video, kwargs", SOLUTIONS)
  173. def test_solution(name, solution_class, needs_frame_count, video, kwargs):
  174. """Test individual Ultralytics solution with video processing and parameter validation."""
  175. if video:
  176. if name != "ObjectCounterVertical":
  177. safe_download(url=f"{ASSETS_URL}/{video}", dir=TMP)
  178. else:
  179. safe_download(url=f"{ASSETS_URL}/{VERTICAL_VIDEO}", dir=TMP)
  180. if name == "ParkingManager":
  181. safe_download(url=f"{ASSETS_URL}/{PARKING_AREAS_JSON}", dir=TMP)
  182. safe_download(url=f"{ASSETS_URL}/{PARKING_MODEL}", dir=TMP)
  183. elif name == "StreamlitInference":
  184. if checks.check_imshow(): # do not merge with elif above
  185. solution_class(**kwargs).inference() # requires interactive GUI environment
  186. return
  187. video = VERTICAL_VIDEO if name == "ObjectCounterVertical" else video
  188. process_video(
  189. solution=solution_class(**kwargs),
  190. video_path=str(TMP / video),
  191. needs_frame_count=needs_frame_count,
  192. )
  193. @pytest.mark.skipif(checks.IS_PYTHON_3_8, reason="Disabled due to unsupported CLIP dependencies.")
  194. @pytest.mark.skipif(IS_RASPBERRYPI, reason="Disabled due to slow performance on Raspberry Pi.")
  195. def test_similarity_search():
  196. """Test similarity search solution with sample images and text query."""
  197. safe_download(f"{ASSETS_URL}/4-imgs-similaritysearch.zip", dir=TMP) # 4 dog images for testing in a zip file
  198. searcher = solutions.VisualAISearch(data=str(TMP / "4-imgs-similaritysearch"))
  199. _ = searcher("a dog sitting on a bench") # Returns the results in format "- img name | similarity score"
  200. def test_left_click_selection():
  201. """Test distance calculation left click selection functionality."""
  202. dc = solutions.DistanceCalculation()
  203. dc.boxes, dc.track_ids = [[10, 10, 50, 50]], [1]
  204. dc.mouse_event_for_distance(cv2.EVENT_LBUTTONDOWN, 30, 30, None, None)
  205. assert 1 in dc.selected_boxes
  206. def test_right_click_reset():
  207. """Test distance calculation right click reset functionality."""
  208. dc = solutions.DistanceCalculation()
  209. dc.selected_boxes, dc.left_mouse_count = {1: [10, 10, 50, 50]}, 1
  210. dc.mouse_event_for_distance(cv2.EVENT_RBUTTONDOWN, 0, 0, None, None)
  211. assert dc.selected_boxes == {}
  212. assert dc.left_mouse_count == 0
  213. def test_parking_json_none():
  214. """Test that ParkingManagement handles missing JSON gracefully."""
  215. im0 = np.zeros((640, 480, 3), dtype=np.uint8)
  216. try:
  217. parkingmanager = solutions.ParkingManagement(json_path=None)
  218. parkingmanager(im0)
  219. except ValueError:
  220. pytest.skip("Skipping test due to missing JSON.")
  221. def test_analytics_graph_not_supported():
  222. """Test that unsupported analytics type raises ModuleNotFoundError."""
  223. try:
  224. analytics = solutions.Analytics(analytics_type="test") # 'test' is unsupported
  225. analytics.process(im0=np.zeros((640, 480, 3), dtype=np.uint8), frame_number=0)
  226. assert False, "Expected ModuleNotFoundError for unsupported chart type"
  227. except ModuleNotFoundError as e:
  228. assert "test chart is not supported" in str(e)
  229. def test_area_chart_padding():
  230. """Test area chart graph update with dynamic class padding logic."""
  231. analytics = solutions.Analytics(analytics_type="area")
  232. analytics.update_graph(frame_number=1, count_dict={"car": 2}, plot="area")
  233. plot_im = analytics.update_graph(frame_number=2, count_dict={"car": 3, "person": 1}, plot="area")
  234. assert plot_im is not None
  235. def test_config_update_method_with_invalid_argument():
  236. """Test that update() raises ValueError for invalid config keys."""
  237. obj = solutions.config.SolutionConfig()
  238. try:
  239. obj.update(invalid_key=123)
  240. assert False, "Expected ValueError for invalid update argument"
  241. except ValueError as e:
  242. assert "is not a valid solution argument" in str(e)
  243. def test_plot_with_no_masks():
  244. """Test that instance segmentation handles cases with no masks."""
  245. im0 = np.zeros((640, 480, 3), dtype=np.uint8)
  246. isegment = solutions.InstanceSegmentation(model="yolo11n-seg.pt")
  247. results = isegment(im0)
  248. assert results.plot_im is not None
  249. def test_streamlit_handle_video_upload_creates_file():
  250. """Test Streamlit video upload logic saves file correctly."""
  251. import io
  252. fake_file = io.BytesIO(b"fake video content")
  253. fake_file.read = fake_file.getvalue
  254. if fake_file is not None:
  255. g = io.BytesIO(fake_file.read())
  256. with open("ultralytics.mp4", "wb") as out:
  257. out.write(g.read())
  258. output_path = "ultralytics.mp4"
  259. else:
  260. output_path = None
  261. assert output_path == "ultralytics.mp4"
  262. assert os.path.exists("ultralytics.mp4")
  263. with open("ultralytics.mp4", "rb") as f:
  264. assert f.read() == b"fake video content"
  265. os.remove("ultralytics.mp4")
  266. @pytest.mark.skipif(checks.IS_PYTHON_3_8, reason="Disabled due to unsupported CLIP dependencies.")
  267. @pytest.mark.skipif(IS_RASPBERRYPI, reason="Disabled due to slow performance on Raspberry Pi.")
  268. def test_similarity_search_app_init():
  269. """Test SearchApp initializes with required attributes."""
  270. app = solutions.SearchApp(device="cpu")
  271. assert hasattr(app, "searcher")
  272. assert hasattr(app, "run")
  273. @pytest.mark.skipif(IS_RASPBERRYPI, reason="Disabled due to slow performance on Raspberry Pi.")
  274. def test_similarity_search_complete(tmp_path):
  275. """Test VisualAISearch end-to-end with sample image and query."""
  276. from PIL import Image
  277. image_dir = tmp_path / "images"
  278. os.makedirs(image_dir, exist_ok=True)
  279. for i in range(2):
  280. img = Image.fromarray(np.uint8(np.random.rand(224, 224, 3) * 255))
  281. img.save(image_dir / f"test_image_{i}.jpg")
  282. searcher = solutions.VisualAISearch(data=str(image_dir))
  283. results = searcher("a red and white object")
  284. assert results
  285. def test_distance_calculation_process_method():
  286. """Test DistanceCalculation.process() computes distance between selected boxes."""
  287. from ultralytics.solutions.solutions import SolutionResults
  288. dc = solutions.DistanceCalculation()
  289. dc.boxes, dc.track_ids, dc.clss, dc.confs = (
  290. [[100, 100, 200, 200], [300, 300, 400, 400]],
  291. [1, 2],
  292. [0, 0],
  293. [0.9, 0.95],
  294. )
  295. dc.selected_boxes = {1: dc.boxes[0], 2: dc.boxes[1]}
  296. frame = np.zeros((480, 640, 3), dtype=np.uint8)
  297. with patch.object(dc, "extract_tracks"), patch.object(dc, "display_output"), patch("cv2.setMouseCallback"):
  298. result = dc.process(frame)
  299. assert isinstance(result, SolutionResults)
  300. assert result.total_tracks == 2
  301. assert result.pixels_distance > 0
  302. def test_object_crop_with_show_True():
  303. """Test ObjectCropper init with show=True to cover display warning."""
  304. solutions.ObjectCropper(show=True)
  305. def test_display_output_method():
  306. """Test that display_output triggers imshow, waitKey, and destroyAllWindows when enabled."""
  307. counter = solutions.ObjectCounter(show=True)
  308. counter.env_check = True
  309. frame = np.zeros((100, 100, 3), dtype=np.uint8)
  310. with patch("cv2.imshow") as mock_imshow, patch("cv2.waitKey", return_value=ord("q")) as mock_wait, patch(
  311. "cv2.destroyAllWindows"
  312. ) as mock_destroy:
  313. counter.display_output(frame)
  314. mock_imshow.assert_called_once()
  315. mock_wait.assert_called_once()
  316. mock_destroy.assert_called_once()
Tip!

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

Comments

Loading...