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 18 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
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import contextlib
  3. from copy import copy
  4. from pathlib import Path
  5. import cv2
  6. import numpy as np
  7. import pytest
  8. import torch
  9. from PIL import Image
  10. from torchvision.transforms import ToTensor
  11. from ultralytics import RTDETR, YOLO
  12. from ultralytics.cfg import TASK2DATA
  13. from ultralytics.data.build import load_inference_source
  14. from ultralytics.utils import (ASSETS, DEFAULT_CFG, DEFAULT_CFG_PATH, LINUX, MACOS, ONLINE, ROOT, WEIGHTS_DIR, WINDOWS,
  15. checks, is_dir_writeable)
  16. from ultralytics.utils.downloads import download
  17. from ultralytics.utils.torch_utils import TORCH_1_9
  18. MODEL = WEIGHTS_DIR / 'path with spaces' / 'yolov8n.pt' # test spaces in path
  19. CFG = 'yolov8n.yaml'
  20. SOURCE = ASSETS / 'bus.jpg'
  21. TMP = (ROOT / '../tests/tmp').resolve() # temp directory for test files
  22. IS_TMP_WRITEABLE = is_dir_writeable(TMP)
  23. def test_model_forward():
  24. """Test the forward pass of the YOLO model."""
  25. model = YOLO(CFG)
  26. model(source=None, imgsz=32, augment=True) # also test no source and augment
  27. def test_model_methods():
  28. """Test various methods and properties of the YOLO model."""
  29. model = YOLO(MODEL)
  30. # Model methods
  31. model.info(verbose=True, detailed=True)
  32. model = model.reset_weights()
  33. model = model.load(MODEL)
  34. model.to('cpu')
  35. model.fuse()
  36. model.clear_callback('on_train_start')
  37. model.reset_callbacks()
  38. # Model properties
  39. _ = model.names
  40. _ = model.device
  41. _ = model.transforms
  42. _ = model.task_map
  43. def test_model_profile():
  44. """Test profiling of the YOLO model with 'profile=True' argument."""
  45. from ultralytics.nn.tasks import DetectionModel
  46. model = DetectionModel() # build model
  47. im = torch.randn(1, 3, 64, 64) # requires min imgsz=64
  48. _ = model.predict(im, profile=True)
  49. @pytest.mark.skipif(not IS_TMP_WRITEABLE, reason='directory is not writeable')
  50. def test_predict_txt():
  51. """Test YOLO predictions with sources (file, dir, glob, recursive glob) specified in a text file."""
  52. txt_file = TMP / 'sources.txt'
  53. with open(txt_file, 'w') as f:
  54. for x in [ASSETS / 'bus.jpg', ASSETS, ASSETS / '*', ASSETS / '**/*.jpg']:
  55. f.write(f'{x}\n')
  56. _ = YOLO(MODEL)(source=txt_file, imgsz=32)
  57. def test_predict_img():
  58. """Test YOLO prediction on various types of image sources."""
  59. model = YOLO(MODEL)
  60. seg_model = YOLO(WEIGHTS_DIR / 'yolov8n-seg.pt')
  61. cls_model = YOLO(WEIGHTS_DIR / 'yolov8n-cls.pt')
  62. pose_model = YOLO(WEIGHTS_DIR / 'yolov8n-pose.pt')
  63. im = cv2.imread(str(SOURCE))
  64. assert len(model(source=Image.open(SOURCE), save=True, verbose=True, imgsz=32)) == 1 # PIL
  65. assert len(model(source=im, save=True, save_txt=True, imgsz=32)) == 1 # ndarray
  66. assert len(model(source=[im, im], save=True, save_txt=True, imgsz=32)) == 2 # batch
  67. assert len(list(model(source=[im, im], save=True, stream=True, imgsz=32))) == 2 # stream
  68. assert len(model(torch.zeros(320, 640, 3).numpy(), imgsz=32)) == 1 # tensor to numpy
  69. batch = [
  70. str(SOURCE), # filename
  71. Path(SOURCE), # Path
  72. 'https://ultralytics.com/images/zidane.jpg' if ONLINE else SOURCE, # URI
  73. cv2.imread(str(SOURCE)), # OpenCV
  74. Image.open(SOURCE), # PIL
  75. np.zeros((320, 640, 3))] # numpy
  76. assert len(model(batch, imgsz=32)) == len(batch) # multiple sources in a batch
  77. # Test tensor inference
  78. im = cv2.imread(str(SOURCE)) # OpenCV
  79. t = cv2.resize(im, (32, 32))
  80. t = ToTensor()(t)
  81. t = torch.stack([t, t, t, t])
  82. results = model(t, imgsz=32)
  83. assert len(results) == t.shape[0]
  84. results = seg_model(t, imgsz=32)
  85. assert len(results) == t.shape[0]
  86. results = cls_model(t, imgsz=32)
  87. assert len(results) == t.shape[0]
  88. results = pose_model(t, imgsz=32)
  89. assert len(results) == t.shape[0]
  90. def test_predict_grey_and_4ch():
  91. """Test YOLO prediction on SOURCE converted to greyscale and 4-channel images."""
  92. im = Image.open(SOURCE)
  93. directory = TMP / 'im4'
  94. directory.mkdir(parents=True, exist_ok=True)
  95. source_greyscale = directory / 'greyscale.jpg'
  96. source_rgba = directory / '4ch.png'
  97. source_non_utf = directory / 'non_UTF_测试文件_tést_image.jpg'
  98. source_spaces = directory / 'image with spaces.jpg'
  99. im.convert('L').save(source_greyscale) # greyscale
  100. im.convert('RGBA').save(source_rgba) # 4-ch PNG with alpha
  101. im.save(source_non_utf) # non-UTF characters in filename
  102. im.save(source_spaces) # spaces in filename
  103. # Inference
  104. model = YOLO(MODEL)
  105. for f in source_rgba, source_greyscale, source_non_utf, source_spaces:
  106. for source in Image.open(f), cv2.imread(str(f)), f:
  107. results = model(source, save=True, verbose=True, imgsz=32)
  108. assert len(results) == 1 # verify that an image was run
  109. f.unlink() # cleanup
  110. @pytest.mark.slow
  111. @pytest.mark.skipif(not ONLINE, reason='environment is offline')
  112. def test_youtube():
  113. """
  114. Test YouTube inference.
  115. Marked --slow to reduce YouTube API rate limits risk.
  116. """
  117. model = YOLO(MODEL)
  118. model.predict('https://youtu.be/G17sBkb38XQ', imgsz=96, save=True)
  119. @pytest.mark.skipif(not ONLINE, reason='environment is offline')
  120. @pytest.mark.skipif(not IS_TMP_WRITEABLE, reason='directory is not writeable')
  121. def test_track_stream():
  122. """
  123. Test streaming tracking (short 10 frame video) with non-default ByteTrack tracker.
  124. Note imgsz=160 required for tracking for higher confidence and better matches
  125. """
  126. import yaml
  127. video_url = 'https://ultralytics.com/assets/decelera_portrait_min.mov'
  128. model = YOLO(MODEL)
  129. model.track(video_url, imgsz=160, tracker='bytetrack.yaml')
  130. model.track(video_url, imgsz=160, tracker='botsort.yaml', save_frames=True) # test frame saving also
  131. # Test Global Motion Compensation (GMC) methods
  132. for gmc in 'orb', 'sift', 'ecc':
  133. with open(ROOT / 'cfg/trackers/botsort.yaml', encoding='utf-8') as f:
  134. data = yaml.safe_load(f)
  135. tracker = TMP / f'botsort-{gmc}.yaml'
  136. data['gmc_method'] = gmc
  137. with open(tracker, 'w', encoding='utf-8') as f:
  138. yaml.safe_dump(data, f)
  139. model.track(video_url, imgsz=160, tracker=tracker)
  140. def test_val():
  141. """Test the validation mode of the YOLO model."""
  142. YOLO(MODEL).val(data='coco8.yaml', imgsz=32, save_hybrid=True)
  143. def test_train_scratch():
  144. """Test training the YOLO model from scratch."""
  145. model = YOLO(CFG)
  146. model.train(data='coco8.yaml', epochs=2, imgsz=32, cache='disk', batch=-1, close_mosaic=1, name='model')
  147. model(SOURCE)
  148. def test_train_pretrained():
  149. """Test training the YOLO model from a pre-trained state."""
  150. model = YOLO(WEIGHTS_DIR / 'yolov8n-seg.pt')
  151. model.train(data='coco8-seg.yaml', epochs=1, imgsz=32, cache='ram', copy_paste=0.5, mixup=0.5, name=0)
  152. model(SOURCE)
  153. def test_export_torchscript():
  154. """Test exporting the YOLO model to TorchScript format."""
  155. f = YOLO(MODEL).export(format='torchscript', optimize=False)
  156. YOLO(f)(SOURCE) # exported model inference
  157. def test_export_onnx():
  158. """Test exporting the YOLO model to ONNX format."""
  159. f = YOLO(MODEL).export(format='onnx', dynamic=True)
  160. YOLO(f)(SOURCE) # exported model inference
  161. def test_export_openvino():
  162. """Test exporting the YOLO model to OpenVINO format."""
  163. f = YOLO(MODEL).export(format='openvino')
  164. YOLO(f)(SOURCE) # exported model inference
  165. def test_export_coreml():
  166. """Test exporting the YOLO model to CoreML format."""
  167. if not WINDOWS: # RuntimeError: BlobWriter not loaded with coremltools 7.0 on windows
  168. if MACOS:
  169. f = YOLO(MODEL).export(format='coreml')
  170. YOLO(f)(SOURCE) # model prediction only supported on macOS for nms=False models
  171. else:
  172. YOLO(MODEL).export(format='coreml', nms=True)
  173. def test_export_tflite(enabled=False):
  174. """
  175. Test exporting the YOLO model to TFLite format.
  176. Note TF suffers from install conflicts on Windows and macOS.
  177. """
  178. if enabled and LINUX:
  179. model = YOLO(MODEL)
  180. f = model.export(format='tflite')
  181. YOLO(f)(SOURCE)
  182. def test_export_pb(enabled=False):
  183. """
  184. Test exporting the YOLO model to *.pb format.
  185. Note TF suffers from install conflicts on Windows and macOS.
  186. """
  187. if enabled and LINUX:
  188. model = YOLO(MODEL)
  189. f = model.export(format='pb')
  190. YOLO(f)(SOURCE)
  191. def test_export_paddle(enabled=False):
  192. """
  193. Test exporting the YOLO model to Paddle format.
  194. Note Paddle protobuf requirements conflicting with onnx protobuf requirements.
  195. """
  196. if enabled:
  197. YOLO(MODEL).export(format='paddle')
  198. @pytest.mark.slow
  199. def test_export_ncnn():
  200. """Test exporting the YOLO model to NCNN format."""
  201. f = YOLO(MODEL).export(format='ncnn')
  202. YOLO(f)(SOURCE) # exported model inference
  203. def test_all_model_yamls():
  204. """Test YOLO model creation for all available YAML configurations."""
  205. for m in (ROOT / 'cfg' / 'models').rglob('*.yaml'):
  206. if 'rtdetr' in m.name:
  207. if TORCH_1_9: # torch<=1.8 issue - TypeError: __init__() got an unexpected keyword argument 'batch_first'
  208. _ = RTDETR(m.name)(SOURCE, imgsz=640) # must be 640
  209. else:
  210. YOLO(m.name)
  211. def test_workflow():
  212. """Test the complete workflow including training, validation, prediction, and exporting."""
  213. model = YOLO(MODEL)
  214. model.train(data='coco8.yaml', epochs=1, imgsz=32, optimizer='SGD')
  215. model.val(imgsz=32)
  216. model.predict(SOURCE, imgsz=32)
  217. model.export(format='onnx') # export a model to ONNX format
  218. def test_predict_callback_and_setup():
  219. """Test callback functionality during YOLO prediction."""
  220. def on_predict_batch_end(predictor):
  221. """Callback function that handles operations at the end of a prediction batch."""
  222. path, im0s, _, _ = predictor.batch
  223. im0s = im0s if isinstance(im0s, list) else [im0s]
  224. bs = [predictor.dataset.bs for _ in range(len(path))]
  225. predictor.results = zip(predictor.results, im0s, bs) # results is List[batch_size]
  226. model = YOLO(MODEL)
  227. model.add_callback('on_predict_batch_end', on_predict_batch_end)
  228. dataset = load_inference_source(source=SOURCE)
  229. bs = dataset.bs # noqa access predictor properties
  230. results = model.predict(dataset, stream=True, imgsz=160) # source already setup
  231. for r, im0, bs in results:
  232. print('test_callback', im0.shape)
  233. print('test_callback', bs)
  234. boxes = r.boxes # Boxes object for bbox outputs
  235. print(boxes)
  236. def test_results():
  237. """Test various result formats for the YOLO model."""
  238. for m in 'yolov8n-pose.pt', 'yolov8n-seg.pt', 'yolov8n.pt', 'yolov8n-cls.pt':
  239. results = YOLO(WEIGHTS_DIR / m)([SOURCE, SOURCE], imgsz=160)
  240. for r in results:
  241. r = r.cpu().numpy()
  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.tojson(normalize=True)
  246. r.plot(pil=True)
  247. r.plot(conf=True, boxes=True)
  248. print(r, len(r), r.path)
  249. @pytest.mark.skipif(not ONLINE, reason='environment is offline')
  250. def test_data_utils():
  251. """Test utility functions in ultralytics/data/utils.py."""
  252. from ultralytics.data.utils import HUBDatasetStats, autosplit
  253. from ultralytics.utils.downloads import zip_directory
  254. # from ultralytics.utils.files import WorkingDirectory
  255. # with WorkingDirectory(ROOT.parent / 'tests'):
  256. for task in 'detect', 'segment', 'pose', 'classify':
  257. file = Path(TASK2DATA[task]).with_suffix('.zip') # i.e. coco8.zip
  258. download(f'https://github.com/ultralytics/hub/raw/main/example_datasets/{file}', unzip=False, dir=TMP)
  259. stats = HUBDatasetStats(TMP / file, task=task)
  260. stats.get_json(save=True)
  261. stats.process_images()
  262. autosplit(TMP / 'coco8')
  263. zip_directory(TMP / 'coco8/images/val') # zip
  264. @pytest.mark.skipif(not ONLINE, reason='environment is offline')
  265. def test_data_converter():
  266. """Test dataset converters."""
  267. from ultralytics.data.converter import coco80_to_coco91_class, convert_coco
  268. file = 'instances_val2017.json'
  269. download(f'https://github.com/ultralytics/yolov5/releases/download/v1.0/{file}', dir=TMP)
  270. convert_coco(labels_dir=TMP, save_dir=TMP / 'yolo_labels', use_segments=True, use_keypoints=False, cls91to80=True)
  271. coco80_to_coco91_class()
  272. def test_data_annotator():
  273. """Test automatic data annotation."""
  274. from ultralytics.data.annotator import auto_annotate
  275. auto_annotate(ASSETS,
  276. det_model=WEIGHTS_DIR / 'yolov8n.pt',
  277. sam_model=WEIGHTS_DIR / 'mobile_sam.pt',
  278. output_dir=TMP / 'auto_annotate_labels')
  279. def test_events():
  280. """Test event sending functionality."""
  281. from ultralytics.hub.utils import Events
  282. events = Events()
  283. events.enabled = True
  284. cfg = copy(DEFAULT_CFG) # does not require deepcopy
  285. cfg.mode = 'test'
  286. events(cfg)
  287. def test_cfg_init():
  288. """Test configuration initialization utilities."""
  289. from ultralytics.cfg import check_dict_alignment, copy_default_cfg, smart_value
  290. with contextlib.suppress(SyntaxError):
  291. check_dict_alignment({'a': 1}, {'b': 2})
  292. copy_default_cfg()
  293. (Path.cwd() / DEFAULT_CFG_PATH.name.replace('.yaml', '_copy.yaml')).unlink(missing_ok=False)
  294. [smart_value(x) for x in ['none', 'true', 'false']]
  295. def test_utils_init():
  296. """Test initialization utilities."""
  297. from ultralytics.utils import get_git_branch, get_git_origin_url, get_ubuntu_version, is_github_action_running
  298. get_ubuntu_version()
  299. is_github_action_running()
  300. get_git_origin_url()
  301. get_git_branch()
  302. def test_utils_checks():
  303. """Test various utility checks."""
  304. checks.check_yolov5u_filename('yolov5n.pt')
  305. checks.git_describe(ROOT)
  306. checks.check_requirements() # check requirements.txt
  307. checks.check_imgsz([600, 600], max_dim=1)
  308. checks.check_imshow()
  309. checks.check_version('ultralytics', '8.0.0')
  310. checks.print_args()
  311. # checks.check_imshow(warn=True)
  312. def test_utils_benchmarks():
  313. """Test model benchmarking."""
  314. from ultralytics.utils.benchmarks import ProfileModels
  315. ProfileModels(['yolov8n.yaml'], imgsz=32, min_time=1, num_timed_runs=3, num_warmup_runs=1).profile()
  316. def test_utils_torchutils():
  317. """Test Torch utility functions."""
  318. from ultralytics.nn.modules.conv import Conv
  319. from ultralytics.utils.torch_utils import get_flops_with_torch_profiler, profile, time_sync
  320. x = torch.randn(1, 64, 20, 20)
  321. m = Conv(64, 64, k=1, s=2)
  322. profile(x, [m], n=3)
  323. get_flops_with_torch_profiler(m)
  324. time_sync()
  325. @pytest.mark.skipif(not ONLINE, reason='environment is offline')
  326. def test_utils_downloads():
  327. """Test file download utilities."""
  328. from ultralytics.utils.downloads import get_google_drive_file_info
  329. get_google_drive_file_info('https://drive.google.com/file/d/1cqT-cJgANNrhIHCrEufUYhQ4RqiWG_lJ/view?usp=drive_link')
  330. def test_utils_ops():
  331. """Test various operations utilities."""
  332. from ultralytics.utils.ops import (ltwh2xywh, ltwh2xyxy, make_divisible, xywh2ltwh, xywh2xyxy, xywhn2xyxy,
  333. xywhr2xyxyxyxy, xyxy2ltwh, xyxy2xywh, xyxy2xywhn, xyxyxyxy2xywhr)
  334. make_divisible(17, torch.tensor([8]))
  335. boxes = torch.rand(10, 4) # xywh
  336. torch.allclose(boxes, xyxy2xywh(xywh2xyxy(boxes)))
  337. torch.allclose(boxes, xyxy2xywhn(xywhn2xyxy(boxes)))
  338. torch.allclose(boxes, ltwh2xywh(xywh2ltwh(boxes)))
  339. torch.allclose(boxes, xyxy2ltwh(ltwh2xyxy(boxes)))
  340. boxes = torch.rand(10, 5) # xywhr for OBB
  341. boxes[:, 4] = torch.randn(10) * 30
  342. torch.allclose(boxes, xyxyxyxy2xywhr(xywhr2xyxyxyxy(boxes)), rtol=1e-3)
  343. def test_utils_files():
  344. """Test file handling utilities."""
  345. from ultralytics.utils.files import file_age, file_date, get_latest_run, spaces_in_path
  346. file_age(SOURCE)
  347. file_date(SOURCE)
  348. get_latest_run(ROOT / 'runs')
  349. path = TMP / 'path/with spaces'
  350. path.mkdir(parents=True, exist_ok=True)
  351. with spaces_in_path(path) as new_path:
  352. print(new_path)
  353. def test_nn_modules_conv():
  354. """Test Convolutional Neural Network modules."""
  355. from ultralytics.nn.modules.conv import CBAM, Conv2, ConvTranspose, DWConvTranspose2d, Focus
  356. c1, c2 = 8, 16 # input and output channels
  357. x = torch.zeros(4, c1, 10, 10) # BCHW
  358. # Run all modules not otherwise covered in tests
  359. DWConvTranspose2d(c1, c2)(x)
  360. ConvTranspose(c1, c2)(x)
  361. Focus(c1, c2)(x)
  362. CBAM(c1)(x)
  363. # Fuse ops
  364. m = Conv2(c1, c2)
  365. m.fuse_convs()
  366. m(x)
  367. def test_nn_modules_block():
  368. """Test Neural Network block modules."""
  369. from ultralytics.nn.modules.block import C1, C3TR, BottleneckCSP, C3Ghost, C3x
  370. c1, c2 = 8, 16 # input and output channels
  371. x = torch.zeros(4, c1, 10, 10) # BCHW
  372. # Run all modules not otherwise covered in tests
  373. C1(c1, c2)(x)
  374. C3x(c1, c2)(x)
  375. C3TR(c1, c2)(x)
  376. C3Ghost(c1, c2)(x)
  377. BottleneckCSP(c1, c2)(x)
  378. @pytest.mark.skipif(not ONLINE, reason='environment is offline')
  379. def test_hub():
  380. """Test Ultralytics HUB functionalities."""
  381. from ultralytics.hub import export_fmts_hub, logout
  382. from ultralytics.hub.utils import smart_request
  383. export_fmts_hub()
  384. logout()
  385. smart_request('GET', 'http://github.com', progress=True)
  386. @pytest.mark.slow
  387. @pytest.mark.skipif(not ONLINE, reason='environment is offline')
  388. def test_model_tune():
  389. """Tune YOLO model for performance."""
  390. YOLO('yolov8n-pose.pt').tune(data='coco8-pose.yaml', plots=False, imgsz=32, epochs=1, iterations=2, device='cpu')
  391. YOLO('yolov8n-cls.pt').tune(data='imagenet10', plots=False, imgsz=32, epochs=1, iterations=2, device='cpu')
Tip!

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

Comments

Loading...