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_python.py 27 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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. import contextlib
  3. import csv
  4. import urllib
  5. from copy import copy
  6. from pathlib import Path
  7. import cv2
  8. import numpy as np
  9. import pytest
  10. import torch
  11. from PIL import Image
  12. from tests import CFG, MODEL, MODELS, SOURCE, SOURCES_LIST, TASK_MODEL_DATA, TMP
  13. from ultralytics import RTDETR, YOLO
  14. from ultralytics.cfg import TASK2DATA, TASKS
  15. from ultralytics.data.build import load_inference_source
  16. from ultralytics.data.utils import check_det_dataset
  17. from ultralytics.utils import (
  18. ARM64,
  19. ASSETS,
  20. DEFAULT_CFG,
  21. DEFAULT_CFG_PATH,
  22. LINUX,
  23. LOGGER,
  24. ONLINE,
  25. ROOT,
  26. WEIGHTS_DIR,
  27. WINDOWS,
  28. YAML,
  29. checks,
  30. is_dir_writeable,
  31. is_github_action_running,
  32. )
  33. from ultralytics.utils.downloads import download
  34. from ultralytics.utils.torch_utils import TORCH_1_9
  35. IS_TMP_WRITEABLE = is_dir_writeable(TMP) # WARNING: must be run once tests start as TMP does not exist on tests/init
  36. def test_model_forward():
  37. """Test the forward pass of the YOLO model."""
  38. model = YOLO(CFG)
  39. model(source=None, imgsz=32, augment=True) # also test no source and augment
  40. def test_model_methods():
  41. """Test various methods and properties of the YOLO model to ensure correct functionality."""
  42. model = YOLO(MODEL)
  43. # Model methods
  44. model.info(verbose=True, detailed=True)
  45. model = model.reset_weights()
  46. model = model.load(MODEL)
  47. model.to("cpu")
  48. model.fuse()
  49. model.clear_callback("on_train_start")
  50. model.reset_callbacks()
  51. # Model properties
  52. _ = model.names
  53. _ = model.device
  54. _ = model.transforms
  55. _ = model.task_map
  56. def test_model_profile():
  57. """Test profiling of the YOLO model with `profile=True` to assess performance and resource usage."""
  58. from ultralytics.nn.tasks import DetectionModel
  59. model = DetectionModel() # build model
  60. im = torch.randn(1, 3, 64, 64) # requires min imgsz=64
  61. _ = model.predict(im, profile=True)
  62. @pytest.mark.skipif(not IS_TMP_WRITEABLE, reason="directory is not writeable")
  63. def test_predict_txt():
  64. """Test YOLO predictions with file, directory, and pattern sources listed in a text file."""
  65. file = TMP / "sources_multi_row.txt"
  66. with open(file, "w") as f:
  67. for src in SOURCES_LIST:
  68. f.write(f"{src}\n")
  69. results = YOLO(MODEL)(source=file, imgsz=32)
  70. assert len(results) == 7 # 1 + 2 + 2 + 2 = 7 images
  71. @pytest.mark.skipif(True, reason="disabled for testing")
  72. @pytest.mark.skipif(not IS_TMP_WRITEABLE, reason="directory is not writeable")
  73. def test_predict_csv_multi_row():
  74. """Test YOLO predictions with sources listed in multiple rows of a CSV file."""
  75. file = TMP / "sources_multi_row.csv"
  76. with open(file, "w", newline="") as f:
  77. writer = csv.writer(f)
  78. writer.writerow(["source"])
  79. writer.writerows([[src] for src in SOURCES_LIST])
  80. results = YOLO(MODEL)(source=file, imgsz=32)
  81. assert len(results) == 7 # 1 + 2 + 2 + 2 = 7 images
  82. @pytest.mark.skipif(True, reason="disabled for testing")
  83. @pytest.mark.skipif(not IS_TMP_WRITEABLE, reason="directory is not writeable")
  84. def test_predict_csv_single_row():
  85. """Test YOLO predictions with sources listed in a single row of a CSV file."""
  86. file = TMP / "sources_single_row.csv"
  87. with open(file, "w", newline="") as f:
  88. writer = csv.writer(f)
  89. writer.writerow(SOURCES_LIST)
  90. results = YOLO(MODEL)(source=file, imgsz=32)
  91. assert len(results) == 7 # 1 + 2 + 2 + 2 = 7 images
  92. @pytest.mark.parametrize("model_name", MODELS)
  93. def test_predict_img(model_name):
  94. """Test YOLO model predictions on various image input types and sources, including online images."""
  95. channels = 1 if model_name == "yolo11n-grayscale.pt" else 3
  96. model = YOLO(WEIGHTS_DIR / model_name)
  97. im = cv2.imread(str(SOURCE), flags=cv2.IMREAD_GRAYSCALE if channels == 1 else cv2.IMREAD_COLOR) # uint8 numpy array
  98. assert len(model(source=Image.open(SOURCE), save=True, verbose=True, imgsz=32)) == 1 # PIL
  99. assert len(model(source=im, save=True, save_txt=True, imgsz=32)) == 1 # ndarray
  100. assert len(model(torch.rand((2, channels, 32, 32)), imgsz=32)) == 2 # batch-size 2 Tensor, FP32 0.0-1.0 RGB order
  101. assert len(model(source=[im, im], save=True, save_txt=True, imgsz=32)) == 2 # batch
  102. assert len(list(model(source=[im, im], save=True, stream=True, imgsz=32))) == 2 # stream
  103. assert len(model(torch.zeros(320, 640, channels).numpy().astype(np.uint8), imgsz=32)) == 1 # tensor to numpy
  104. batch = [
  105. str(SOURCE), # filename
  106. Path(SOURCE), # Path
  107. "https://github.com/ultralytics/assets/releases/download/v0.0.0/zidane.jpg" if ONLINE else SOURCE, # URI
  108. im, # OpenCV
  109. Image.open(SOURCE), # PIL
  110. np.zeros((320, 640, channels), dtype=np.uint8), # numpy
  111. ]
  112. assert len(model(batch, imgsz=32, classes=0)) == len(batch) # multiple sources in a batch
  113. @pytest.mark.parametrize("model", MODELS)
  114. def test_predict_visualize(model):
  115. """Test model prediction methods with 'visualize=True' to generate and display prediction visualizations."""
  116. YOLO(WEIGHTS_DIR / model)(SOURCE, imgsz=32, visualize=True)
  117. def test_predict_grey_and_4ch():
  118. """Test YOLO prediction on SOURCE converted to greyscale and 4-channel images with various filenames."""
  119. im = Image.open(SOURCE)
  120. directory = TMP / "im4"
  121. directory.mkdir(parents=True, exist_ok=True)
  122. source_greyscale = directory / "greyscale.jpg"
  123. source_rgba = directory / "4ch.png"
  124. source_non_utf = directory / "non_UTF_测试文件_tést_image.jpg"
  125. source_spaces = directory / "image with spaces.jpg"
  126. im.convert("L").save(source_greyscale) # greyscale
  127. im.convert("RGBA").save(source_rgba) # 4-ch PNG with alpha
  128. im.save(source_non_utf) # non-UTF characters in filename
  129. im.save(source_spaces) # spaces in filename
  130. # Inference
  131. model = YOLO(MODEL)
  132. for f in source_rgba, source_greyscale, source_non_utf, source_spaces:
  133. for source in Image.open(f), cv2.imread(str(f)), f:
  134. results = model(source, save=True, verbose=True, imgsz=32)
  135. assert len(results) == 1 # verify that an image was run
  136. f.unlink() # cleanup
  137. @pytest.mark.slow
  138. @pytest.mark.skipif(not ONLINE, reason="environment is offline")
  139. @pytest.mark.skipif(is_github_action_running(), reason="No auth https://github.com/JuanBindez/pytubefix/issues/166")
  140. def test_youtube():
  141. """Test YOLO model on a YouTube video stream, handling potential network-related errors."""
  142. model = YOLO(MODEL)
  143. try:
  144. model.predict("https://youtu.be/G17sBkb38XQ", imgsz=96, save=True)
  145. # Handle internet connection errors and 'urllib.error.HTTPError: HTTP Error 429: Too Many Requests'
  146. except (urllib.error.HTTPError, ConnectionError) as e:
  147. LOGGER.error(f"YouTube Test Error: {e}")
  148. @pytest.mark.skipif(not ONLINE, reason="environment is offline")
  149. @pytest.mark.skipif(not IS_TMP_WRITEABLE, reason="directory is not writeable")
  150. @pytest.mark.parametrize("model", MODELS)
  151. def test_track_stream(model):
  152. """
  153. Test streaming tracking on a short 10 frame video using ByteTrack tracker and different GMC methods.
  154. Note imgsz=160 required for tracking for higher confidence and better matches.
  155. """
  156. if model == "yolo11n-cls.pt": # classification model not supported for tracking
  157. return
  158. video_url = "https://github.com/ultralytics/assets/releases/download/v0.0.0/decelera_portrait_min.mov"
  159. model = YOLO(model)
  160. model.track(video_url, imgsz=160, tracker="bytetrack.yaml")
  161. model.track(video_url, imgsz=160, tracker="botsort.yaml", save_frames=True) # test frame saving also
  162. # Test Global Motion Compensation (GMC) methods and ReID
  163. for gmc, reidm in zip(["orb", "sift", "ecc"], ["auto", "auto", "yolo11n-cls.pt"]):
  164. default_args = YAML.load(ROOT / "cfg/trackers/botsort.yaml")
  165. custom_yaml = TMP / f"botsort-{gmc}.yaml"
  166. YAML.save(custom_yaml, {**default_args, "gmc_method": gmc, "with_reid": True, "model": reidm})
  167. model.track(video_url, imgsz=160, tracker=custom_yaml)
  168. @pytest.mark.parametrize("task,weight,data", TASK_MODEL_DATA)
  169. def test_val(task: str, weight: str, data: str) -> None:
  170. """Test the validation mode of the YOLO model."""
  171. model = YOLO(weight)
  172. for plots in {True, False}: # Test both cases i.e. plots=True and plots=False
  173. metrics = model.val(data=data, imgsz=32, plots=plots)
  174. metrics.to_df()
  175. metrics.to_csv()
  176. metrics.to_xml()
  177. metrics.to_html()
  178. metrics.to_json()
  179. metrics.to_sql()
  180. metrics.confusion_matrix.to_df() # Tests for confusion matrix export
  181. metrics.confusion_matrix.to_csv()
  182. metrics.confusion_matrix.to_xml()
  183. metrics.confusion_matrix.to_html()
  184. metrics.confusion_matrix.to_json()
  185. metrics.confusion_matrix.to_sql()
  186. def test_train_scratch():
  187. """Test training the YOLO model from scratch using the provided configuration."""
  188. model = YOLO(CFG)
  189. model.train(data="coco8.yaml", epochs=2, imgsz=32, cache="disk", batch=-1, close_mosaic=1, name="model")
  190. model(SOURCE)
  191. @pytest.mark.parametrize("scls", [False, True])
  192. def test_train_pretrained(scls):
  193. """Test training of the YOLO model starting from a pre-trained checkpoint."""
  194. model = YOLO(WEIGHTS_DIR / "yolo11n-seg.pt")
  195. model.train(
  196. data="coco8-seg.yaml", epochs=1, imgsz=32, cache="ram", copy_paste=0.5, mixup=0.5, name=0, single_cls=scls
  197. )
  198. model(SOURCE)
  199. def test_all_model_yamls():
  200. """Test YOLO model creation for all available YAML configurations in the `cfg/models` directory."""
  201. for m in (ROOT / "cfg" / "models").rglob("*.yaml"):
  202. if "rtdetr" in m.name:
  203. if TORCH_1_9: # torch<=1.8 issue - TypeError: __init__() got an unexpected keyword argument 'batch_first'
  204. _ = RTDETR(m.name)(SOURCE, imgsz=640) # must be 640
  205. else:
  206. YOLO(m.name)
  207. @pytest.mark.skipif(WINDOWS, reason="Windows slow CI export bug https://github.com/ultralytics/ultralytics/pull/16003")
  208. def test_workflow():
  209. """Test the complete workflow including training, validation, prediction, and exporting."""
  210. model = YOLO(MODEL)
  211. model.train(data="coco8.yaml", epochs=1, imgsz=32, optimizer="SGD")
  212. model.val(imgsz=32)
  213. model.predict(SOURCE, imgsz=32)
  214. model.export(format="torchscript") # WARNING: Windows slow CI export bug
  215. def test_predict_callback_and_setup():
  216. """Test callback functionality during YOLO prediction setup and execution."""
  217. def on_predict_batch_end(predictor):
  218. """Callback function that handles operations at the end of a prediction batch."""
  219. path, im0s, _ = predictor.batch
  220. im0s = im0s if isinstance(im0s, list) else [im0s]
  221. bs = [predictor.dataset.bs for _ in range(len(path))]
  222. predictor.results = zip(predictor.results, im0s, bs) # results is List[batch_size]
  223. model = YOLO(MODEL)
  224. model.add_callback("on_predict_batch_end", on_predict_batch_end)
  225. dataset = load_inference_source(source=SOURCE)
  226. bs = dataset.bs # noqa access predictor properties
  227. results = model.predict(dataset, stream=True, imgsz=160) # source already setup
  228. for r, im0, bs in results:
  229. print("test_callback", im0.shape)
  230. print("test_callback", bs)
  231. boxes = r.boxes # Boxes object for bbox outputs
  232. print(boxes)
  233. @pytest.mark.parametrize("model", MODELS)
  234. def test_results(model: str):
  235. """Test YOLO model results processing and output in various formats."""
  236. temp_s = "https://ultralytics.com/images/boats.jpg" if model == "yolo11n-obb.pt" else SOURCE
  237. results = YOLO(WEIGHTS_DIR / model)([temp_s, temp_s], imgsz=160)
  238. for r in results:
  239. assert len(r), f"'{model}' results should not be empty!"
  240. r = r.cpu().numpy()
  241. print(r, len(r), r.path) # print numpy attributes
  242. r = r.to(device="cpu", dtype=torch.float32)
  243. r.save_txt(txt_file=TMP / "runs/tests/label.txt", save_conf=True)
  244. r.save_crop(save_dir=TMP / "runs/tests/crops/")
  245. r.to_df(decimals=3) # Align to_ methods: https://docs.ultralytics.com/modes/predict/#working-with-results
  246. r.to_csv()
  247. r.to_xml()
  248. r.to_html()
  249. r.to_json(normalize=True)
  250. r.to_sql()
  251. r.plot(pil=True, save=True, filename=TMP / "results_plot_save.jpg")
  252. r.plot(conf=True, boxes=True)
  253. print(r, len(r), r.path) # print after methods
  254. def test_labels_and_crops():
  255. """Test output from prediction args for saving YOLO detection labels and crops."""
  256. imgs = [SOURCE, ASSETS / "zidane.jpg"]
  257. results = YOLO(WEIGHTS_DIR / "yolo11n.pt")(imgs, imgsz=160, save_txt=True, save_crop=True)
  258. save_path = Path(results[0].save_dir)
  259. for r in results:
  260. im_name = Path(r.path).stem
  261. cls_idxs = r.boxes.cls.int().tolist()
  262. # Check correct detections
  263. assert cls_idxs == ([0, 7, 0, 0] if r.path.endswith("bus.jpg") else [0, 0, 0]) # bus.jpg and zidane.jpg classes
  264. # Check label path
  265. labels = save_path / f"labels/{im_name}.txt"
  266. assert labels.exists()
  267. # Check detections match label count
  268. assert len(r.boxes.data) == len([line for line in labels.read_text().splitlines() if line])
  269. # Check crops path and files
  270. crop_dirs = list((save_path / "crops").iterdir())
  271. crop_files = [f for p in crop_dirs for f in p.glob("*")]
  272. # Crop directories match detections
  273. assert all(r.names.get(c) in {d.name for d in crop_dirs} for c in cls_idxs)
  274. # Same number of crops as detections
  275. assert len([f for f in crop_files if im_name in f.name]) == len(r.boxes.data)
  276. @pytest.mark.skipif(not ONLINE, reason="environment is offline")
  277. def test_data_utils():
  278. """Test utility functions in ultralytics/data/utils.py, including dataset stats and auto-splitting."""
  279. from ultralytics.data.split import autosplit
  280. from ultralytics.data.utils import HUBDatasetStats
  281. from ultralytics.utils.downloads import zip_directory
  282. # from ultralytics.utils.files import WorkingDirectory
  283. # with WorkingDirectory(ROOT.parent / 'tests'):
  284. for task in TASKS:
  285. file = Path(TASK2DATA[task]).with_suffix(".zip") # i.e. coco8.zip
  286. download(f"https://github.com/ultralytics/hub/raw/main/example_datasets/{file}", unzip=False, dir=TMP)
  287. stats = HUBDatasetStats(TMP / file, task=task)
  288. stats.get_json(save=True)
  289. stats.process_images()
  290. autosplit(TMP / "coco8")
  291. zip_directory(TMP / "coco8/images/val") # zip
  292. @pytest.mark.skipif(not ONLINE, reason="environment is offline")
  293. def test_data_converter():
  294. """Test dataset conversion functions from COCO to YOLO format and class mappings."""
  295. from ultralytics.data.converter import coco80_to_coco91_class, convert_coco
  296. file = "instances_val2017.json"
  297. download(f"https://github.com/ultralytics/assets/releases/download/v0.0.0/{file}", dir=TMP)
  298. convert_coco(labels_dir=TMP, save_dir=TMP / "yolo_labels", use_segments=True, use_keypoints=False, cls91to80=True)
  299. coco80_to_coco91_class()
  300. def test_data_annotator():
  301. """Test automatic annotation of data using detection and segmentation models."""
  302. from ultralytics.data.annotator import auto_annotate
  303. auto_annotate(
  304. ASSETS,
  305. det_model=WEIGHTS_DIR / "yolo11n.pt",
  306. sam_model=WEIGHTS_DIR / "mobile_sam.pt",
  307. output_dir=TMP / "auto_annotate_labels",
  308. )
  309. def test_events():
  310. """Test event sending functionality."""
  311. from ultralytics.hub.utils import Events
  312. events = Events()
  313. events.enabled = True
  314. cfg = copy(DEFAULT_CFG) # does not require deepcopy
  315. cfg.mode = "test"
  316. events(cfg)
  317. def test_cfg_init():
  318. """Test configuration initialization utilities from the 'ultralytics.cfg' module."""
  319. from ultralytics.cfg import check_dict_alignment, copy_default_cfg, smart_value
  320. with contextlib.suppress(SyntaxError):
  321. check_dict_alignment({"a": 1}, {"b": 2})
  322. copy_default_cfg()
  323. (Path.cwd() / DEFAULT_CFG_PATH.name.replace(".yaml", "_copy.yaml")).unlink(missing_ok=False)
  324. [smart_value(x) for x in {"none", "true", "false"}]
  325. def test_utils_init():
  326. """Test initialization utilities in the Ultralytics library."""
  327. from ultralytics.utils import get_git_branch, get_git_origin_url, get_ubuntu_version, is_github_action_running
  328. get_ubuntu_version()
  329. is_github_action_running()
  330. get_git_origin_url()
  331. get_git_branch()
  332. def test_utils_checks():
  333. """Test various utility checks for filenames, git status, requirements, image sizes, and versions."""
  334. checks.check_yolov5u_filename("yolov5n.pt")
  335. checks.git_describe(ROOT)
  336. checks.check_requirements() # check requirements.txt
  337. checks.check_imgsz([600, 600], max_dim=1)
  338. checks.check_imshow(warn=True)
  339. checks.check_version("ultralytics", "8.0.0")
  340. checks.print_args()
  341. @pytest.mark.skipif(WINDOWS, reason="Windows profiling is extremely slow (cause unknown)")
  342. def test_utils_benchmarks():
  343. """Benchmark model performance using 'ProfileModels' from 'ultralytics.utils.benchmarks'."""
  344. from ultralytics.utils.benchmarks import ProfileModels
  345. ProfileModels(["yolo11n.yaml"], imgsz=32, min_time=1, num_timed_runs=3, num_warmup_runs=1).run()
  346. def test_utils_torchutils():
  347. """Test Torch utility functions including profiling and FLOP calculations."""
  348. from ultralytics.nn.modules.conv import Conv
  349. from ultralytics.utils.torch_utils import get_flops_with_torch_profiler, profile_ops, time_sync
  350. x = torch.randn(1, 64, 20, 20)
  351. m = Conv(64, 64, k=1, s=2)
  352. profile_ops(x, [m], n=3)
  353. get_flops_with_torch_profiler(m)
  354. time_sync()
  355. def test_utils_ops():
  356. """Test utility operations for coordinate transformations and normalizations."""
  357. from ultralytics.utils.ops import (
  358. ltwh2xywh,
  359. ltwh2xyxy,
  360. make_divisible,
  361. xywh2ltwh,
  362. xywh2xyxy,
  363. xywhn2xyxy,
  364. xywhr2xyxyxyxy,
  365. xyxy2ltwh,
  366. xyxy2xywh,
  367. xyxy2xywhn,
  368. xyxyxyxy2xywhr,
  369. )
  370. make_divisible(17, torch.tensor([8]))
  371. boxes = torch.rand(10, 4) # xywh
  372. torch.allclose(boxes, xyxy2xywh(xywh2xyxy(boxes)))
  373. torch.allclose(boxes, xyxy2xywhn(xywhn2xyxy(boxes)))
  374. torch.allclose(boxes, ltwh2xywh(xywh2ltwh(boxes)))
  375. torch.allclose(boxes, xyxy2ltwh(ltwh2xyxy(boxes)))
  376. boxes = torch.rand(10, 5) # xywhr for OBB
  377. boxes[:, 4] = torch.randn(10) * 30
  378. torch.allclose(boxes, xyxyxyxy2xywhr(xywhr2xyxyxyxy(boxes)), rtol=1e-3)
  379. def test_utils_files():
  380. """Test file handling utilities including file age, date, and paths with spaces."""
  381. from ultralytics.utils.files import file_age, file_date, get_latest_run, spaces_in_path
  382. file_age(SOURCE)
  383. file_date(SOURCE)
  384. get_latest_run(ROOT / "runs")
  385. path = TMP / "path/with spaces"
  386. path.mkdir(parents=True, exist_ok=True)
  387. with spaces_in_path(path) as new_path:
  388. print(new_path)
  389. @pytest.mark.slow
  390. def test_utils_patches_torch_save():
  391. """Test torch_save backoff when _torch_save raises RuntimeError."""
  392. from unittest.mock import MagicMock, patch
  393. from ultralytics.utils.patches import torch_save
  394. mock = MagicMock(side_effect=RuntimeError)
  395. with patch("ultralytics.utils.patches._torch_save", new=mock):
  396. with pytest.raises(RuntimeError):
  397. torch_save(torch.zeros(1), TMP / "test.pt")
  398. assert mock.call_count == 4, "torch_save was not attempted the expected number of times"
  399. def test_nn_modules_conv():
  400. """Test Convolutional Neural Network modules including CBAM, Conv2, and ConvTranspose."""
  401. from ultralytics.nn.modules.conv import CBAM, Conv2, ConvTranspose, DWConvTranspose2d, Focus
  402. c1, c2 = 8, 16 # input and output channels
  403. x = torch.zeros(4, c1, 10, 10) # BCHW
  404. # Run all modules not otherwise covered in tests
  405. DWConvTranspose2d(c1, c2)(x)
  406. ConvTranspose(c1, c2)(x)
  407. Focus(c1, c2)(x)
  408. CBAM(c1)(x)
  409. # Fuse ops
  410. m = Conv2(c1, c2)
  411. m.fuse_convs()
  412. m(x)
  413. def test_nn_modules_block():
  414. """Test various neural network block modules."""
  415. from ultralytics.nn.modules.block import C1, C3TR, BottleneckCSP, C3Ghost, C3x
  416. c1, c2 = 8, 16 # input and output channels
  417. x = torch.zeros(4, c1, 10, 10) # BCHW
  418. # Run all modules not otherwise covered in tests
  419. C1(c1, c2)(x)
  420. C3x(c1, c2)(x)
  421. C3TR(c1, c2)(x)
  422. C3Ghost(c1, c2)(x)
  423. BottleneckCSP(c1, c2)(x)
  424. @pytest.mark.skipif(not ONLINE, reason="environment is offline")
  425. def test_hub():
  426. """Test Ultralytics HUB functionalities."""
  427. from ultralytics.hub import export_fmts_hub, logout
  428. from ultralytics.hub.utils import smart_request
  429. export_fmts_hub()
  430. logout()
  431. smart_request("GET", "https://github.com", progress=True)
  432. @pytest.fixture
  433. def image():
  434. """Load and return an image from a predefined source."""
  435. return cv2.imread(str(SOURCE))
  436. @pytest.mark.parametrize(
  437. "auto_augment, erasing, force_color_jitter",
  438. [
  439. (None, 0.0, False),
  440. ("randaugment", 0.5, True),
  441. ("augmix", 0.2, False),
  442. ("autoaugment", 0.0, True),
  443. ],
  444. )
  445. def test_classify_transforms_train(image, auto_augment, erasing, force_color_jitter):
  446. """Test classification transforms during training with various augmentations."""
  447. from ultralytics.data.augment import classify_augmentations
  448. transform = classify_augmentations(
  449. size=224,
  450. mean=(0.5, 0.5, 0.5),
  451. std=(0.5, 0.5, 0.5),
  452. scale=(0.08, 1.0),
  453. ratio=(3.0 / 4.0, 4.0 / 3.0),
  454. hflip=0.5,
  455. vflip=0.5,
  456. auto_augment=auto_augment,
  457. hsv_h=0.015,
  458. hsv_s=0.4,
  459. hsv_v=0.4,
  460. force_color_jitter=force_color_jitter,
  461. erasing=erasing,
  462. )
  463. transformed_image = transform(Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)))
  464. assert transformed_image.shape == (3, 224, 224)
  465. assert torch.is_tensor(transformed_image)
  466. assert transformed_image.dtype == torch.float32
  467. @pytest.mark.slow
  468. @pytest.mark.skipif(not ONLINE, reason="environment is offline")
  469. def test_model_tune():
  470. """Tune YOLO model for performance improvement."""
  471. YOLO("yolo11n-pose.pt").tune(data="coco8-pose.yaml", plots=False, imgsz=32, epochs=1, iterations=2, device="cpu")
  472. YOLO("yolo11n-cls.pt").tune(data="imagenet10", plots=False, imgsz=32, epochs=1, iterations=2, device="cpu")
  473. def test_model_embeddings():
  474. """Test YOLO model embeddings extraction functionality."""
  475. model_detect = YOLO(MODEL)
  476. model_segment = YOLO(WEIGHTS_DIR / "yolo11n-seg.pt")
  477. for batch in [SOURCE], [SOURCE, SOURCE]: # test batch size 1 and 2
  478. assert len(model_detect.embed(source=batch, imgsz=32)) == len(batch)
  479. assert len(model_segment.embed(source=batch, imgsz=32)) == len(batch)
  480. @pytest.mark.skipif(checks.IS_PYTHON_3_12, reason="YOLOWorld with CLIP is not supported in Python 3.12")
  481. @pytest.mark.skipif(
  482. checks.IS_PYTHON_3_8 and LINUX and ARM64,
  483. reason="YOLOWorld with CLIP is not supported in Python 3.8 and aarch64 Linux",
  484. )
  485. def test_yolo_world():
  486. """Test YOLO world models with CLIP support."""
  487. model = YOLO(WEIGHTS_DIR / "yolov8s-world.pt") # no YOLO11n-world model yet
  488. model.set_classes(["tree", "window"])
  489. model(SOURCE, conf=0.01)
  490. model = YOLO(WEIGHTS_DIR / "yolov8s-worldv2.pt") # no YOLO11n-world model yet
  491. # Training from a pretrained model. Eval is included at the final stage of training.
  492. # Use dota8.yaml which has fewer categories to reduce the inference time of CLIP model
  493. model.train(
  494. data="dota8.yaml",
  495. epochs=1,
  496. imgsz=32,
  497. cache="disk",
  498. close_mosaic=1,
  499. )
  500. # test WorWorldTrainerFromScratch
  501. from ultralytics.models.yolo.world.train_world import WorldTrainerFromScratch
  502. model = YOLO("yolov8s-worldv2.yaml") # no YOLO11n-world model yet
  503. model.train(
  504. data={"train": {"yolo_data": ["dota8.yaml"]}, "val": {"yolo_data": ["dota8.yaml"]}},
  505. epochs=1,
  506. imgsz=32,
  507. cache="disk",
  508. close_mosaic=1,
  509. trainer=WorldTrainerFromScratch,
  510. )
  511. @pytest.mark.skipif(checks.IS_PYTHON_3_12 or not TORCH_1_9, reason="YOLOE with CLIP is not supported in Python 3.12")
  512. @pytest.mark.skipif(
  513. checks.IS_PYTHON_3_8 and LINUX and ARM64,
  514. reason="YOLOE with CLIP is not supported in Python 3.8 and aarch64 Linux",
  515. )
  516. def test_yoloe():
  517. """Test YOLOE models with MobileClip support."""
  518. # Predict
  519. # text-prompts
  520. model = YOLO(WEIGHTS_DIR / "yoloe-11s-seg.pt")
  521. names = ["person", "bus"]
  522. model.set_classes(names, model.get_text_pe(names))
  523. model(SOURCE, conf=0.01)
  524. import numpy as np
  525. from ultralytics import YOLOE
  526. from ultralytics.models.yolo.yoloe import YOLOEVPSegPredictor
  527. # visual-prompts
  528. visuals = dict(
  529. bboxes=np.array(
  530. [[221.52, 405.8, 344.98, 857.54], [120, 425, 160, 445]],
  531. ),
  532. cls=np.array([0, 1]),
  533. )
  534. model.predict(
  535. SOURCE,
  536. visual_prompts=visuals,
  537. predictor=YOLOEVPSegPredictor,
  538. )
  539. # Val
  540. model = YOLOE(WEIGHTS_DIR / "yoloe-11s-seg.pt")
  541. # text prompts
  542. model.val(data="coco128-seg.yaml", imgsz=32)
  543. # visual prompts
  544. model.val(data="coco128-seg.yaml", load_vp=True, imgsz=32)
  545. # Train, fine-tune
  546. from ultralytics.models.yolo.yoloe import YOLOEPESegTrainer
  547. model = YOLOE("yoloe-11s-seg.pt")
  548. model.train(
  549. data="coco128-seg.yaml",
  550. epochs=1,
  551. close_mosaic=1,
  552. trainer=YOLOEPESegTrainer,
  553. imgsz=32,
  554. )
  555. # prompt-free
  556. # predict
  557. model = YOLOE(WEIGHTS_DIR / "yoloe-11s-seg-pf.pt")
  558. model.predict(SOURCE)
  559. # val
  560. model = YOLOE("yoloe-11s-seg.pt") # or select yoloe-m/l-seg.pt for different sizes
  561. model.val(data="coco128-seg.yaml", imgsz=32)
  562. def test_yolov10():
  563. """Test YOLOv10 model training, validation, and prediction functionality."""
  564. model = YOLO("yolov10n.yaml")
  565. # train/val/predict
  566. model.train(data="coco8.yaml", epochs=1, imgsz=32, close_mosaic=1, cache="disk")
  567. model.val(data="coco8.yaml", imgsz=32)
  568. model.predict(imgsz=32, save_txt=True, save_crop=True, augment=True)
  569. model(SOURCE)
  570. def test_multichannel():
  571. """Test YOLO model multi-channel training, validation, and prediction functionality."""
  572. model = YOLO("yolo11n.pt")
  573. model.train(data="coco8-multispectral.yaml", epochs=1, imgsz=32, close_mosaic=1, cache="disk")
  574. model.val(data="coco8-multispectral.yaml")
  575. im = np.zeros((32, 32, 10), dtype=np.uint8)
  576. model.predict(source=im, imgsz=32, save_txt=True, save_crop=True, augment=True)
  577. model.export(format="onnx")
  578. @pytest.mark.parametrize("task,model,data", TASK_MODEL_DATA)
  579. def test_grayscale(task: str, model: str, data: str) -> None:
  580. """Test YOLO model grayscale training, validation, and prediction functionality."""
  581. if task == "classify": # not support grayscale classification yet
  582. return
  583. grayscale_data = Path(TMP) / f"{Path(data).stem}-grayscale.yaml"
  584. data = check_det_dataset(data)
  585. data["channels"] = 1 # add additional channels key for grayscale
  586. YAML.save(grayscale_data, data)
  587. # remove npy files in train/val splits if exists, might be created by previous tests
  588. for split in {"train", "val"}:
  589. for npy_file in (Path(data["path"]) / data[split]).glob("*.npy"):
  590. npy_file.unlink()
  591. model = YOLO(model)
  592. model.train(data=grayscale_data, epochs=1, imgsz=32, close_mosaic=1)
  593. model.val(data=grayscale_data)
  594. im = np.zeros((32, 32, 1), dtype=np.uint8)
  595. model.predict(source=im, imgsz=32, save_txt=True, save_crop=True, augment=True)
  596. export_model = model.export(format="onnx")
  597. model = YOLO(export_model, task=task)
  598. model.predict(source=im, imgsz=32)
Tip!

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

Comments

Loading...