ultralytics 8.1.28__py3-none-any.whl → 8.3.62__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (247) hide show
  1. tests/__init__.py +22 -0
  2. tests/conftest.py +83 -0
  3. tests/test_cli.py +122 -0
  4. tests/test_cuda.py +155 -0
  5. tests/test_engine.py +131 -0
  6. tests/test_exports.py +216 -0
  7. tests/test_integrations.py +150 -0
  8. tests/test_python.py +615 -0
  9. tests/test_solutions.py +94 -0
  10. ultralytics/__init__.py +11 -8
  11. ultralytics/cfg/__init__.py +569 -131
  12. ultralytics/cfg/datasets/Argoverse.yaml +2 -1
  13. ultralytics/cfg/datasets/DOTAv1.5.yaml +3 -2
  14. ultralytics/cfg/datasets/DOTAv1.yaml +3 -2
  15. ultralytics/cfg/datasets/GlobalWheat2020.yaml +3 -2
  16. ultralytics/cfg/datasets/ImageNet.yaml +2 -1
  17. ultralytics/cfg/datasets/Objects365.yaml +5 -4
  18. ultralytics/cfg/datasets/SKU-110K.yaml +2 -1
  19. ultralytics/cfg/datasets/VOC.yaml +3 -2
  20. ultralytics/cfg/datasets/VisDrone.yaml +6 -5
  21. ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
  22. ultralytics/cfg/datasets/brain-tumor.yaml +23 -0
  23. ultralytics/cfg/datasets/carparts-seg.yaml +3 -2
  24. ultralytics/cfg/datasets/coco-pose.yaml +7 -6
  25. ultralytics/cfg/datasets/coco.yaml +3 -2
  26. ultralytics/cfg/datasets/coco128-seg.yaml +4 -3
  27. ultralytics/cfg/datasets/coco128.yaml +4 -3
  28. ultralytics/cfg/datasets/coco8-pose.yaml +3 -2
  29. ultralytics/cfg/datasets/coco8-seg.yaml +3 -2
  30. ultralytics/cfg/datasets/coco8.yaml +3 -2
  31. ultralytics/cfg/datasets/crack-seg.yaml +3 -2
  32. ultralytics/cfg/datasets/dog-pose.yaml +24 -0
  33. ultralytics/cfg/datasets/dota8.yaml +3 -2
  34. ultralytics/cfg/datasets/hand-keypoints.yaml +26 -0
  35. ultralytics/cfg/datasets/lvis.yaml +1236 -0
  36. ultralytics/cfg/datasets/medical-pills.yaml +22 -0
  37. ultralytics/cfg/datasets/open-images-v7.yaml +2 -1
  38. ultralytics/cfg/datasets/package-seg.yaml +5 -4
  39. ultralytics/cfg/datasets/signature.yaml +21 -0
  40. ultralytics/cfg/datasets/tiger-pose.yaml +3 -2
  41. ultralytics/cfg/datasets/xView.yaml +2 -1
  42. ultralytics/cfg/default.yaml +14 -11
  43. ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +24 -0
  44. ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
  45. ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
  46. ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
  47. ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
  48. ultralytics/cfg/models/11/yolo11.yaml +50 -0
  49. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +5 -2
  50. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +5 -2
  51. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +5 -2
  52. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +5 -2
  53. ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
  54. ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
  55. ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
  56. ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
  57. ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
  58. ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
  59. ultralytics/cfg/models/v3/yolov3-spp.yaml +5 -2
  60. ultralytics/cfg/models/v3/yolov3-tiny.yaml +5 -2
  61. ultralytics/cfg/models/v3/yolov3.yaml +5 -2
  62. ultralytics/cfg/models/v5/yolov5-p6.yaml +5 -2
  63. ultralytics/cfg/models/v5/yolov5.yaml +5 -2
  64. ultralytics/cfg/models/v6/yolov6.yaml +5 -2
  65. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +5 -2
  66. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +5 -2
  67. ultralytics/cfg/models/v8/yolov8-cls.yaml +5 -2
  68. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +6 -2
  69. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +6 -2
  70. ultralytics/cfg/models/v8/yolov8-ghost.yaml +5 -2
  71. ultralytics/cfg/models/v8/yolov8-obb.yaml +5 -2
  72. ultralytics/cfg/models/v8/yolov8-p2.yaml +5 -2
  73. ultralytics/cfg/models/v8/yolov8-p6.yaml +10 -7
  74. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +5 -2
  75. ultralytics/cfg/models/v8/yolov8-pose.yaml +5 -2
  76. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +5 -2
  77. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +5 -2
  78. ultralytics/cfg/models/v8/yolov8-seg.yaml +5 -2
  79. ultralytics/cfg/models/v8/yolov8-world.yaml +5 -2
  80. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +5 -2
  81. ultralytics/cfg/models/v8/yolov8.yaml +5 -2
  82. ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
  83. ultralytics/cfg/models/v9/yolov9c.yaml +30 -25
  84. ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
  85. ultralytics/cfg/models/v9/yolov9e.yaml +46 -42
  86. ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
  87. ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
  88. ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
  89. ultralytics/cfg/solutions/default.yaml +24 -0
  90. ultralytics/cfg/trackers/botsort.yaml +8 -5
  91. ultralytics/cfg/trackers/bytetrack.yaml +8 -5
  92. ultralytics/data/__init__.py +14 -3
  93. ultralytics/data/annotator.py +37 -15
  94. ultralytics/data/augment.py +1783 -289
  95. ultralytics/data/base.py +62 -27
  96. ultralytics/data/build.py +36 -8
  97. ultralytics/data/converter.py +196 -36
  98. ultralytics/data/dataset.py +233 -94
  99. ultralytics/data/loaders.py +199 -96
  100. ultralytics/data/split_dota.py +39 -29
  101. ultralytics/data/utils.py +110 -40
  102. ultralytics/engine/__init__.py +1 -1
  103. ultralytics/engine/exporter.py +569 -242
  104. ultralytics/engine/model.py +604 -252
  105. ultralytics/engine/predictor.py +22 -11
  106. ultralytics/engine/results.py +1228 -218
  107. ultralytics/engine/trainer.py +190 -129
  108. ultralytics/engine/tuner.py +18 -18
  109. ultralytics/engine/validator.py +18 -15
  110. ultralytics/hub/__init__.py +31 -13
  111. ultralytics/hub/auth.py +11 -7
  112. ultralytics/hub/google/__init__.py +159 -0
  113. ultralytics/hub/session.py +128 -94
  114. ultralytics/hub/utils.py +20 -21
  115. ultralytics/models/__init__.py +4 -2
  116. ultralytics/models/fastsam/__init__.py +2 -3
  117. ultralytics/models/fastsam/model.py +26 -4
  118. ultralytics/models/fastsam/predict.py +127 -63
  119. ultralytics/models/fastsam/utils.py +1 -44
  120. ultralytics/models/fastsam/val.py +1 -1
  121. ultralytics/models/nas/__init__.py +1 -1
  122. ultralytics/models/nas/model.py +21 -10
  123. ultralytics/models/nas/predict.py +3 -6
  124. ultralytics/models/nas/val.py +4 -4
  125. ultralytics/models/rtdetr/__init__.py +1 -1
  126. ultralytics/models/rtdetr/model.py +1 -1
  127. ultralytics/models/rtdetr/predict.py +6 -8
  128. ultralytics/models/rtdetr/train.py +6 -2
  129. ultralytics/models/rtdetr/val.py +3 -3
  130. ultralytics/models/sam/__init__.py +3 -3
  131. ultralytics/models/sam/amg.py +29 -23
  132. ultralytics/models/sam/build.py +211 -13
  133. ultralytics/models/sam/model.py +91 -30
  134. ultralytics/models/sam/modules/__init__.py +1 -1
  135. ultralytics/models/sam/modules/blocks.py +1129 -0
  136. ultralytics/models/sam/modules/decoders.py +381 -53
  137. ultralytics/models/sam/modules/encoders.py +515 -324
  138. ultralytics/models/sam/modules/memory_attention.py +237 -0
  139. ultralytics/models/sam/modules/sam.py +969 -21
  140. ultralytics/models/sam/modules/tiny_encoder.py +425 -154
  141. ultralytics/models/sam/modules/transformer.py +159 -60
  142. ultralytics/models/sam/modules/utils.py +293 -0
  143. ultralytics/models/sam/predict.py +1263 -132
  144. ultralytics/models/utils/__init__.py +1 -1
  145. ultralytics/models/utils/loss.py +36 -24
  146. ultralytics/models/utils/ops.py +3 -7
  147. ultralytics/models/yolo/__init__.py +3 -3
  148. ultralytics/models/yolo/classify/__init__.py +1 -1
  149. ultralytics/models/yolo/classify/predict.py +7 -8
  150. ultralytics/models/yolo/classify/train.py +17 -22
  151. ultralytics/models/yolo/classify/val.py +8 -4
  152. ultralytics/models/yolo/detect/__init__.py +1 -1
  153. ultralytics/models/yolo/detect/predict.py +3 -5
  154. ultralytics/models/yolo/detect/train.py +11 -4
  155. ultralytics/models/yolo/detect/val.py +90 -52
  156. ultralytics/models/yolo/model.py +14 -9
  157. ultralytics/models/yolo/obb/__init__.py +1 -1
  158. ultralytics/models/yolo/obb/predict.py +2 -2
  159. ultralytics/models/yolo/obb/train.py +5 -3
  160. ultralytics/models/yolo/obb/val.py +41 -23
  161. ultralytics/models/yolo/pose/__init__.py +1 -1
  162. ultralytics/models/yolo/pose/predict.py +3 -5
  163. ultralytics/models/yolo/pose/train.py +2 -2
  164. ultralytics/models/yolo/pose/val.py +51 -17
  165. ultralytics/models/yolo/segment/__init__.py +1 -1
  166. ultralytics/models/yolo/segment/predict.py +3 -5
  167. ultralytics/models/yolo/segment/train.py +2 -2
  168. ultralytics/models/yolo/segment/val.py +60 -19
  169. ultralytics/models/yolo/world/__init__.py +5 -0
  170. ultralytics/models/yolo/world/train.py +92 -0
  171. ultralytics/models/yolo/world/train_world.py +109 -0
  172. ultralytics/nn/__init__.py +1 -1
  173. ultralytics/nn/autobackend.py +228 -93
  174. ultralytics/nn/modules/__init__.py +39 -14
  175. ultralytics/nn/modules/activation.py +21 -0
  176. ultralytics/nn/modules/block.py +527 -67
  177. ultralytics/nn/modules/conv.py +24 -7
  178. ultralytics/nn/modules/head.py +177 -34
  179. ultralytics/nn/modules/transformer.py +6 -5
  180. ultralytics/nn/modules/utils.py +1 -2
  181. ultralytics/nn/tasks.py +225 -77
  182. ultralytics/solutions/__init__.py +30 -1
  183. ultralytics/solutions/ai_gym.py +96 -143
  184. ultralytics/solutions/analytics.py +247 -0
  185. ultralytics/solutions/distance_calculation.py +78 -135
  186. ultralytics/solutions/heatmap.py +93 -247
  187. ultralytics/solutions/object_counter.py +184 -259
  188. ultralytics/solutions/parking_management.py +246 -0
  189. ultralytics/solutions/queue_management.py +112 -0
  190. ultralytics/solutions/region_counter.py +116 -0
  191. ultralytics/solutions/security_alarm.py +144 -0
  192. ultralytics/solutions/solutions.py +178 -0
  193. ultralytics/solutions/speed_estimation.py +86 -174
  194. ultralytics/solutions/streamlit_inference.py +190 -0
  195. ultralytics/solutions/trackzone.py +68 -0
  196. ultralytics/trackers/__init__.py +1 -1
  197. ultralytics/trackers/basetrack.py +32 -13
  198. ultralytics/trackers/bot_sort.py +61 -28
  199. ultralytics/trackers/byte_tracker.py +83 -51
  200. ultralytics/trackers/track.py +21 -6
  201. ultralytics/trackers/utils/__init__.py +1 -1
  202. ultralytics/trackers/utils/gmc.py +62 -48
  203. ultralytics/trackers/utils/kalman_filter.py +166 -35
  204. ultralytics/trackers/utils/matching.py +40 -21
  205. ultralytics/utils/__init__.py +511 -239
  206. ultralytics/utils/autobatch.py +40 -22
  207. ultralytics/utils/benchmarks.py +266 -85
  208. ultralytics/utils/callbacks/__init__.py +1 -1
  209. ultralytics/utils/callbacks/base.py +1 -3
  210. ultralytics/utils/callbacks/clearml.py +7 -6
  211. ultralytics/utils/callbacks/comet.py +39 -17
  212. ultralytics/utils/callbacks/dvc.py +1 -1
  213. ultralytics/utils/callbacks/hub.py +16 -16
  214. ultralytics/utils/callbacks/mlflow.py +28 -24
  215. ultralytics/utils/callbacks/neptune.py +6 -2
  216. ultralytics/utils/callbacks/raytune.py +3 -4
  217. ultralytics/utils/callbacks/tensorboard.py +18 -18
  218. ultralytics/utils/callbacks/wb.py +27 -20
  219. ultralytics/utils/checks.py +160 -100
  220. ultralytics/utils/dist.py +2 -1
  221. ultralytics/utils/downloads.py +44 -37
  222. ultralytics/utils/errors.py +1 -1
  223. ultralytics/utils/files.py +72 -38
  224. ultralytics/utils/instance.py +41 -19
  225. ultralytics/utils/loss.py +84 -56
  226. ultralytics/utils/metrics.py +61 -56
  227. ultralytics/utils/ops.py +94 -89
  228. ultralytics/utils/patches.py +30 -14
  229. ultralytics/utils/plotting.py +600 -269
  230. ultralytics/utils/tal.py +67 -26
  231. ultralytics/utils/torch_utils.py +302 -102
  232. ultralytics/utils/triton.py +2 -1
  233. ultralytics/utils/tuner.py +21 -12
  234. ultralytics-8.3.62.dist-info/METADATA +370 -0
  235. ultralytics-8.3.62.dist-info/RECORD +241 -0
  236. {ultralytics-8.1.28.dist-info → ultralytics-8.3.62.dist-info}/WHEEL +1 -1
  237. ultralytics/data/explorer/__init__.py +0 -5
  238. ultralytics/data/explorer/explorer.py +0 -472
  239. ultralytics/data/explorer/gui/__init__.py +0 -1
  240. ultralytics/data/explorer/gui/dash.py +0 -268
  241. ultralytics/data/explorer/utils.py +0 -166
  242. ultralytics/models/fastsam/prompt.py +0 -357
  243. ultralytics-8.1.28.dist-info/METADATA +0 -373
  244. ultralytics-8.1.28.dist-info/RECORD +0 -197
  245. {ultralytics-8.1.28.dist-info → ultralytics-8.3.62.dist-info}/LICENSE +0 -0
  246. {ultralytics-8.1.28.dist-info → ultralytics-8.3.62.dist-info}/entry_points.txt +0 -0
  247. {ultralytics-8.1.28.dist-info → ultralytics-8.3.62.dist-info}/top_level.txt +0 -0
tests/test_python.py ADDED
@@ -0,0 +1,615 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ import contextlib
4
+ import csv
5
+ import urllib
6
+ from copy import copy
7
+ from pathlib import Path
8
+
9
+ import cv2
10
+ import numpy as np
11
+ import pytest
12
+ import torch
13
+ import yaml
14
+ from PIL import Image
15
+
16
+ from tests import CFG, MODEL, SOURCE, SOURCES_LIST, TMP
17
+ from ultralytics import RTDETR, YOLO
18
+ from ultralytics.cfg import MODELS, TASK2DATA, TASKS
19
+ from ultralytics.data.build import load_inference_source
20
+ from ultralytics.utils import (
21
+ ASSETS,
22
+ DEFAULT_CFG,
23
+ DEFAULT_CFG_PATH,
24
+ LOGGER,
25
+ ONLINE,
26
+ ROOT,
27
+ WEIGHTS_DIR,
28
+ WINDOWS,
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
+
36
+ IS_TMP_WRITEABLE = is_dir_writeable(TMP) # WARNING: must be run once tests start as TMP does not exist on tests/init
37
+
38
+
39
+ def test_model_forward():
40
+ """Test the forward pass of the YOLO model."""
41
+ model = YOLO(CFG)
42
+ model(source=None, imgsz=32, augment=True) # also test no source and augment
43
+
44
+
45
+ def test_model_methods():
46
+ """Test various methods and properties of the YOLO model to ensure correct functionality."""
47
+ model = YOLO(MODEL)
48
+
49
+ # Model methods
50
+ model.info(verbose=True, detailed=True)
51
+ model = model.reset_weights()
52
+ model = model.load(MODEL)
53
+ model.to("cpu")
54
+ model.fuse()
55
+ model.clear_callback("on_train_start")
56
+ model.reset_callbacks()
57
+
58
+ # Model properties
59
+ _ = model.names
60
+ _ = model.device
61
+ _ = model.transforms
62
+ _ = model.task_map
63
+
64
+
65
+ def test_model_profile():
66
+ """Test profiling of the YOLO model with `profile=True` to assess performance and resource usage."""
67
+ from ultralytics.nn.tasks import DetectionModel
68
+
69
+ model = DetectionModel() # build model
70
+ im = torch.randn(1, 3, 64, 64) # requires min imgsz=64
71
+ _ = model.predict(im, profile=True)
72
+
73
+
74
+ @pytest.mark.skipif(not IS_TMP_WRITEABLE, reason="directory is not writeable")
75
+ def test_predict_txt():
76
+ """Tests YOLO predictions with file, directory, and pattern sources listed in a text file."""
77
+ file = TMP / "sources_multi_row.txt"
78
+ with open(file, "w") as f:
79
+ for src in SOURCES_LIST:
80
+ f.write(f"{src}\n")
81
+ results = YOLO(MODEL)(source=file, imgsz=32)
82
+ assert len(results) == 7 # 1 + 2 + 2 + 2 = 7 images
83
+
84
+
85
+ @pytest.mark.skipif(True, reason="disabled for testing")
86
+ @pytest.mark.skipif(not IS_TMP_WRITEABLE, reason="directory is not writeable")
87
+ def test_predict_csv_multi_row():
88
+ """Tests YOLO predictions with sources listed in multiple rows of a CSV file."""
89
+ file = TMP / "sources_multi_row.csv"
90
+ with open(file, "w", newline="") as f:
91
+ writer = csv.writer(f)
92
+ writer.writerow(["source"])
93
+ writer.writerows([[src] for src in SOURCES_LIST])
94
+ results = YOLO(MODEL)(source=file, imgsz=32)
95
+ assert len(results) == 7 # 1 + 2 + 2 + 2 = 7 images
96
+
97
+
98
+ @pytest.mark.skipif(True, reason="disabled for testing")
99
+ @pytest.mark.skipif(not IS_TMP_WRITEABLE, reason="directory is not writeable")
100
+ def test_predict_csv_single_row():
101
+ """Tests YOLO predictions with sources listed in a single row of a CSV file."""
102
+ file = TMP / "sources_single_row.csv"
103
+ with open(file, "w", newline="") as f:
104
+ writer = csv.writer(f)
105
+ writer.writerow(SOURCES_LIST)
106
+ results = YOLO(MODEL)(source=file, imgsz=32)
107
+ assert len(results) == 7 # 1 + 2 + 2 + 2 = 7 images
108
+
109
+
110
+ @pytest.mark.parametrize("model_name", MODELS)
111
+ def test_predict_img(model_name):
112
+ """Test YOLO model predictions on various image input types and sources, including online images."""
113
+ model = YOLO(WEIGHTS_DIR / model_name)
114
+ im = cv2.imread(str(SOURCE)) # uint8 numpy array
115
+ assert len(model(source=Image.open(SOURCE), save=True, verbose=True, imgsz=32)) == 1 # PIL
116
+ assert len(model(source=im, save=True, save_txt=True, imgsz=32)) == 1 # ndarray
117
+ assert len(model(torch.rand((2, 3, 32, 32)), imgsz=32)) == 2 # batch-size 2 Tensor, FP32 0.0-1.0 RGB order
118
+ assert len(model(source=[im, im], save=True, save_txt=True, imgsz=32)) == 2 # batch
119
+ assert len(list(model(source=[im, im], save=True, stream=True, imgsz=32))) == 2 # stream
120
+ assert len(model(torch.zeros(320, 640, 3).numpy().astype(np.uint8), imgsz=32)) == 1 # tensor to numpy
121
+ batch = [
122
+ str(SOURCE), # filename
123
+ Path(SOURCE), # Path
124
+ "https://github.com/ultralytics/assets/releases/download/v0.0.0/zidane.jpg" if ONLINE else SOURCE, # URI
125
+ cv2.imread(str(SOURCE)), # OpenCV
126
+ Image.open(SOURCE), # PIL
127
+ np.zeros((320, 640, 3), dtype=np.uint8), # numpy
128
+ ]
129
+ assert len(model(batch, imgsz=32)) == len(batch) # multiple sources in a batch
130
+
131
+
132
+ @pytest.mark.parametrize("model", MODELS)
133
+ def test_predict_visualize(model):
134
+ """Test model prediction methods with 'visualize=True' to generate and display prediction visualizations."""
135
+ YOLO(WEIGHTS_DIR / model)(SOURCE, imgsz=32, visualize=True)
136
+
137
+
138
+ def test_predict_grey_and_4ch():
139
+ """Test YOLO prediction on SOURCE converted to greyscale and 4-channel images with various filenames."""
140
+ im = Image.open(SOURCE)
141
+ directory = TMP / "im4"
142
+ directory.mkdir(parents=True, exist_ok=True)
143
+
144
+ source_greyscale = directory / "greyscale.jpg"
145
+ source_rgba = directory / "4ch.png"
146
+ source_non_utf = directory / "non_UTF_测试文件_tést_image.jpg"
147
+ source_spaces = directory / "image with spaces.jpg"
148
+
149
+ im.convert("L").save(source_greyscale) # greyscale
150
+ im.convert("RGBA").save(source_rgba) # 4-ch PNG with alpha
151
+ im.save(source_non_utf) # non-UTF characters in filename
152
+ im.save(source_spaces) # spaces in filename
153
+
154
+ # Inference
155
+ model = YOLO(MODEL)
156
+ for f in source_rgba, source_greyscale, source_non_utf, source_spaces:
157
+ for source in Image.open(f), cv2.imread(str(f)), f:
158
+ results = model(source, save=True, verbose=True, imgsz=32)
159
+ assert len(results) == 1 # verify that an image was run
160
+ f.unlink() # cleanup
161
+
162
+
163
+ @pytest.mark.slow
164
+ @pytest.mark.skipif(not ONLINE, reason="environment is offline")
165
+ @pytest.mark.skipif(is_github_action_running(), reason="No auth https://github.com/JuanBindez/pytubefix/issues/166")
166
+ def test_youtube():
167
+ """Test YOLO model on a YouTube video stream, handling potential network-related errors."""
168
+ model = YOLO(MODEL)
169
+ try:
170
+ model.predict("https://youtu.be/G17sBkb38XQ", imgsz=96, save=True)
171
+ # Handle internet connection errors and 'urllib.error.HTTPError: HTTP Error 429: Too Many Requests'
172
+ except (urllib.error.HTTPError, ConnectionError) as e:
173
+ LOGGER.warning(f"WARNING: YouTube Test Error: {e}")
174
+
175
+
176
+ @pytest.mark.skipif(not ONLINE, reason="environment is offline")
177
+ @pytest.mark.skipif(not IS_TMP_WRITEABLE, reason="directory is not writeable")
178
+ def test_track_stream():
179
+ """
180
+ Tests streaming tracking on a short 10 frame video using ByteTrack tracker and different GMC methods.
181
+
182
+ Note imgsz=160 required for tracking for higher confidence and better matches.
183
+ """
184
+ video_url = "https://github.com/ultralytics/assets/releases/download/v0.0.0/decelera_portrait_min.mov"
185
+ model = YOLO(MODEL)
186
+ model.track(video_url, imgsz=160, tracker="bytetrack.yaml")
187
+ model.track(video_url, imgsz=160, tracker="botsort.yaml", save_frames=True) # test frame saving also
188
+
189
+ # Test Global Motion Compensation (GMC) methods
190
+ for gmc in "orb", "sift", "ecc":
191
+ with open(ROOT / "cfg/trackers/botsort.yaml", encoding="utf-8") as f:
192
+ data = yaml.safe_load(f)
193
+ tracker = TMP / f"botsort-{gmc}.yaml"
194
+ data["gmc_method"] = gmc
195
+ with open(tracker, "w", encoding="utf-8") as f:
196
+ yaml.safe_dump(data, f)
197
+ model.track(video_url, imgsz=160, tracker=tracker)
198
+
199
+
200
+ def test_val():
201
+ """Test the validation mode of the YOLO model."""
202
+ YOLO(MODEL).val(data="coco8.yaml", imgsz=32, save_hybrid=True)
203
+
204
+
205
+ def test_train_scratch():
206
+ """Test training the YOLO model from scratch using the provided configuration."""
207
+ model = YOLO(CFG)
208
+ model.train(data="coco8.yaml", epochs=2, imgsz=32, cache="disk", batch=-1, close_mosaic=1, name="model")
209
+ model(SOURCE)
210
+
211
+
212
+ def test_train_pretrained():
213
+ """Test training of the YOLO model starting from a pre-trained checkpoint."""
214
+ model = YOLO(WEIGHTS_DIR / "yolo11n-seg.pt")
215
+ model.train(data="coco8-seg.yaml", epochs=1, imgsz=32, cache="ram", copy_paste=0.5, mixup=0.5, name=0)
216
+ model(SOURCE)
217
+
218
+
219
+ def test_all_model_yamls():
220
+ """Test YOLO model creation for all available YAML configurations in the `cfg/models` directory."""
221
+ for m in (ROOT / "cfg" / "models").rglob("*.yaml"):
222
+ if "rtdetr" in m.name:
223
+ if TORCH_1_9: # torch<=1.8 issue - TypeError: __init__() got an unexpected keyword argument 'batch_first'
224
+ _ = RTDETR(m.name)(SOURCE, imgsz=640) # must be 640
225
+ else:
226
+ YOLO(m.name)
227
+
228
+
229
+ @pytest.mark.skipif(WINDOWS, reason="Windows slow CI export bug https://github.com/ultralytics/ultralytics/pull/16003")
230
+ def test_workflow():
231
+ """Test the complete workflow including training, validation, prediction, and exporting."""
232
+ model = YOLO(MODEL)
233
+ model.train(data="coco8.yaml", epochs=1, imgsz=32, optimizer="SGD")
234
+ model.val(imgsz=32)
235
+ model.predict(SOURCE, imgsz=32)
236
+ model.export(format="torchscript") # WARNING: Windows slow CI export bug
237
+
238
+
239
+ def test_predict_callback_and_setup():
240
+ """Test callback functionality during YOLO prediction setup and execution."""
241
+
242
+ def on_predict_batch_end(predictor):
243
+ """Callback function that handles operations at the end of a prediction batch."""
244
+ path, im0s, _ = predictor.batch
245
+ im0s = im0s if isinstance(im0s, list) else [im0s]
246
+ bs = [predictor.dataset.bs for _ in range(len(path))]
247
+ predictor.results = zip(predictor.results, im0s, bs) # results is List[batch_size]
248
+
249
+ model = YOLO(MODEL)
250
+ model.add_callback("on_predict_batch_end", on_predict_batch_end)
251
+
252
+ dataset = load_inference_source(source=SOURCE)
253
+ bs = dataset.bs # noqa access predictor properties
254
+ results = model.predict(dataset, stream=True, imgsz=160) # source already setup
255
+ for r, im0, bs in results:
256
+ print("test_callback", im0.shape)
257
+ print("test_callback", bs)
258
+ boxes = r.boxes # Boxes object for bbox outputs
259
+ print(boxes)
260
+
261
+
262
+ @pytest.mark.parametrize("model", MODELS)
263
+ def test_results(model):
264
+ """Ensure YOLO model predictions can be processed and printed in various formats."""
265
+ results = YOLO(WEIGHTS_DIR / model)([SOURCE, SOURCE], imgsz=160)
266
+ for r in results:
267
+ r = r.cpu().numpy()
268
+ print(r, len(r), r.path) # print numpy attributes
269
+ r = r.to(device="cpu", dtype=torch.float32)
270
+ r.save_txt(txt_file=TMP / "runs/tests/label.txt", save_conf=True)
271
+ r.save_crop(save_dir=TMP / "runs/tests/crops/")
272
+ r.to_json(normalize=True)
273
+ r.to_df(decimals=3)
274
+ r.to_csv()
275
+ r.to_xml()
276
+ r.plot(pil=True)
277
+ r.plot(conf=True, boxes=True)
278
+ print(r, len(r), r.path) # print after methods
279
+
280
+
281
+ def test_labels_and_crops():
282
+ """Test output from prediction args for saving YOLO detection labels and crops; ensures accurate saving."""
283
+ imgs = [SOURCE, ASSETS / "zidane.jpg"]
284
+ results = YOLO(WEIGHTS_DIR / "yolo11n.pt")(imgs, imgsz=160, save_txt=True, save_crop=True)
285
+ save_path = Path(results[0].save_dir)
286
+ for r in results:
287
+ im_name = Path(r.path).stem
288
+ cls_idxs = r.boxes.cls.int().tolist()
289
+ # Check correct detections
290
+ assert cls_idxs == ([0, 7, 0, 0] if r.path.endswith("bus.jpg") else [0, 0, 0]) # bus.jpg and zidane.jpg classes
291
+ # Check label path
292
+ labels = save_path / f"labels/{im_name}.txt"
293
+ assert labels.exists()
294
+ # Check detections match label count
295
+ assert len(r.boxes.data) == len([line for line in labels.read_text().splitlines() if line])
296
+ # Check crops path and files
297
+ crop_dirs = list((save_path / "crops").iterdir())
298
+ crop_files = [f for p in crop_dirs for f in p.glob("*")]
299
+ # Crop directories match detections
300
+ assert all(r.names.get(c) in {d.name for d in crop_dirs} for c in cls_idxs)
301
+ # Same number of crops as detections
302
+ assert len([f for f in crop_files if im_name in f.name]) == len(r.boxes.data)
303
+
304
+
305
+ @pytest.mark.skipif(not ONLINE, reason="environment is offline")
306
+ def test_data_utils():
307
+ """Test utility functions in ultralytics/data/utils.py, including dataset stats and auto-splitting."""
308
+ from ultralytics.data.utils import HUBDatasetStats, autosplit
309
+ from ultralytics.utils.downloads import zip_directory
310
+
311
+ # from ultralytics.utils.files import WorkingDirectory
312
+ # with WorkingDirectory(ROOT.parent / 'tests'):
313
+
314
+ for task in TASKS:
315
+ file = Path(TASK2DATA[task]).with_suffix(".zip") # i.e. coco8.zip
316
+ download(f"https://github.com/ultralytics/hub/raw/main/example_datasets/{file}", unzip=False, dir=TMP)
317
+ stats = HUBDatasetStats(TMP / file, task=task)
318
+ stats.get_json(save=True)
319
+ stats.process_images()
320
+
321
+ autosplit(TMP / "coco8")
322
+ zip_directory(TMP / "coco8/images/val") # zip
323
+
324
+
325
+ @pytest.mark.skipif(not ONLINE, reason="environment is offline")
326
+ def test_data_converter():
327
+ """Test dataset conversion functions from COCO to YOLO format and class mappings."""
328
+ from ultralytics.data.converter import coco80_to_coco91_class, convert_coco
329
+
330
+ file = "instances_val2017.json"
331
+ download(f"https://github.com/ultralytics/assets/releases/download/v0.0.0/{file}", dir=TMP)
332
+ convert_coco(labels_dir=TMP, save_dir=TMP / "yolo_labels", use_segments=True, use_keypoints=False, cls91to80=True)
333
+ coco80_to_coco91_class()
334
+
335
+
336
+ def test_data_annotator():
337
+ """Automatically annotate data using specified detection and segmentation models."""
338
+ from ultralytics.data.annotator import auto_annotate
339
+
340
+ auto_annotate(
341
+ ASSETS,
342
+ det_model=WEIGHTS_DIR / "yolo11n.pt",
343
+ sam_model=WEIGHTS_DIR / "mobile_sam.pt",
344
+ output_dir=TMP / "auto_annotate_labels",
345
+ )
346
+
347
+
348
+ def test_events():
349
+ """Test event sending functionality."""
350
+ from ultralytics.hub.utils import Events
351
+
352
+ events = Events()
353
+ events.enabled = True
354
+ cfg = copy(DEFAULT_CFG) # does not require deepcopy
355
+ cfg.mode = "test"
356
+ events(cfg)
357
+
358
+
359
+ def test_cfg_init():
360
+ """Test configuration initialization utilities from the 'ultralytics.cfg' module."""
361
+ from ultralytics.cfg import check_dict_alignment, copy_default_cfg, smart_value
362
+
363
+ with contextlib.suppress(SyntaxError):
364
+ check_dict_alignment({"a": 1}, {"b": 2})
365
+ copy_default_cfg()
366
+ (Path.cwd() / DEFAULT_CFG_PATH.name.replace(".yaml", "_copy.yaml")).unlink(missing_ok=False)
367
+ [smart_value(x) for x in ["none", "true", "false"]]
368
+
369
+
370
+ def test_utils_init():
371
+ """Test initialization utilities in the Ultralytics library."""
372
+ from ultralytics.utils import get_git_branch, get_git_origin_url, get_ubuntu_version, is_github_action_running
373
+
374
+ get_ubuntu_version()
375
+ is_github_action_running()
376
+ get_git_origin_url()
377
+ get_git_branch()
378
+
379
+
380
+ def test_utils_checks():
381
+ """Test various utility checks for filenames, git status, requirements, image sizes, and versions."""
382
+ checks.check_yolov5u_filename("yolov5n.pt")
383
+ checks.git_describe(ROOT)
384
+ checks.check_requirements() # check requirements.txt
385
+ checks.check_imgsz([600, 600], max_dim=1)
386
+ checks.check_imshow(warn=True)
387
+ checks.check_version("ultralytics", "8.0.0")
388
+ checks.print_args()
389
+
390
+
391
+ @pytest.mark.skipif(WINDOWS, reason="Windows profiling is extremely slow (cause unknown)")
392
+ def test_utils_benchmarks():
393
+ """Benchmark model performance using 'ProfileModels' from 'ultralytics.utils.benchmarks'."""
394
+ from ultralytics.utils.benchmarks import ProfileModels
395
+
396
+ ProfileModels(["yolo11n.yaml"], imgsz=32, min_time=1, num_timed_runs=3, num_warmup_runs=1).profile()
397
+
398
+
399
+ def test_utils_torchutils():
400
+ """Test Torch utility functions including profiling and FLOP calculations."""
401
+ from ultralytics.nn.modules.conv import Conv
402
+ from ultralytics.utils.torch_utils import get_flops_with_torch_profiler, profile, time_sync
403
+
404
+ x = torch.randn(1, 64, 20, 20)
405
+ m = Conv(64, 64, k=1, s=2)
406
+
407
+ profile(x, [m], n=3)
408
+ get_flops_with_torch_profiler(m)
409
+ time_sync()
410
+
411
+
412
+ def test_utils_ops():
413
+ """Test utility operations functions for coordinate transformation and normalization."""
414
+ from ultralytics.utils.ops import (
415
+ ltwh2xywh,
416
+ ltwh2xyxy,
417
+ make_divisible,
418
+ xywh2ltwh,
419
+ xywh2xyxy,
420
+ xywhn2xyxy,
421
+ xywhr2xyxyxyxy,
422
+ xyxy2ltwh,
423
+ xyxy2xywh,
424
+ xyxy2xywhn,
425
+ xyxyxyxy2xywhr,
426
+ )
427
+
428
+ make_divisible(17, torch.tensor([8]))
429
+
430
+ boxes = torch.rand(10, 4) # xywh
431
+ torch.allclose(boxes, xyxy2xywh(xywh2xyxy(boxes)))
432
+ torch.allclose(boxes, xyxy2xywhn(xywhn2xyxy(boxes)))
433
+ torch.allclose(boxes, ltwh2xywh(xywh2ltwh(boxes)))
434
+ torch.allclose(boxes, xyxy2ltwh(ltwh2xyxy(boxes)))
435
+
436
+ boxes = torch.rand(10, 5) # xywhr for OBB
437
+ boxes[:, 4] = torch.randn(10) * 30
438
+ torch.allclose(boxes, xyxyxyxy2xywhr(xywhr2xyxyxyxy(boxes)), rtol=1e-3)
439
+
440
+
441
+ def test_utils_files():
442
+ """Test file handling utilities including file age, date, and paths with spaces."""
443
+ from ultralytics.utils.files import file_age, file_date, get_latest_run, spaces_in_path
444
+
445
+ file_age(SOURCE)
446
+ file_date(SOURCE)
447
+ get_latest_run(ROOT / "runs")
448
+
449
+ path = TMP / "path/with spaces"
450
+ path.mkdir(parents=True, exist_ok=True)
451
+ with spaces_in_path(path) as new_path:
452
+ print(new_path)
453
+
454
+
455
+ @pytest.mark.slow
456
+ def test_utils_patches_torch_save():
457
+ """Test torch_save backoff when _torch_save raises RuntimeError to ensure robustness."""
458
+ from unittest.mock import MagicMock, patch
459
+
460
+ from ultralytics.utils.patches import torch_save
461
+
462
+ mock = MagicMock(side_effect=RuntimeError)
463
+
464
+ with patch("ultralytics.utils.patches._torch_save", new=mock):
465
+ with pytest.raises(RuntimeError):
466
+ torch_save(torch.zeros(1), TMP / "test.pt")
467
+
468
+ assert mock.call_count == 4, "torch_save was not attempted the expected number of times"
469
+
470
+
471
+ def test_nn_modules_conv():
472
+ """Test Convolutional Neural Network modules including CBAM, Conv2, and ConvTranspose."""
473
+ from ultralytics.nn.modules.conv import CBAM, Conv2, ConvTranspose, DWConvTranspose2d, Focus
474
+
475
+ c1, c2 = 8, 16 # input and output channels
476
+ x = torch.zeros(4, c1, 10, 10) # BCHW
477
+
478
+ # Run all modules not otherwise covered in tests
479
+ DWConvTranspose2d(c1, c2)(x)
480
+ ConvTranspose(c1, c2)(x)
481
+ Focus(c1, c2)(x)
482
+ CBAM(c1)(x)
483
+
484
+ # Fuse ops
485
+ m = Conv2(c1, c2)
486
+ m.fuse_convs()
487
+ m(x)
488
+
489
+
490
+ def test_nn_modules_block():
491
+ """Test various blocks in neural network modules including C1, C3TR, BottleneckCSP, C3Ghost, and C3x."""
492
+ from ultralytics.nn.modules.block import C1, C3TR, BottleneckCSP, C3Ghost, C3x
493
+
494
+ c1, c2 = 8, 16 # input and output channels
495
+ x = torch.zeros(4, c1, 10, 10) # BCHW
496
+
497
+ # Run all modules not otherwise covered in tests
498
+ C1(c1, c2)(x)
499
+ C3x(c1, c2)(x)
500
+ C3TR(c1, c2)(x)
501
+ C3Ghost(c1, c2)(x)
502
+ BottleneckCSP(c1, c2)(x)
503
+
504
+
505
+ @pytest.mark.skipif(not ONLINE, reason="environment is offline")
506
+ def test_hub():
507
+ """Test Ultralytics HUB functionalities (e.g. export formats, logout)."""
508
+ from ultralytics.hub import export_fmts_hub, logout
509
+ from ultralytics.hub.utils import smart_request
510
+
511
+ export_fmts_hub()
512
+ logout()
513
+ smart_request("GET", "https://github.com", progress=True)
514
+
515
+
516
+ @pytest.fixture
517
+ def image():
518
+ """Load and return an image from a predefined source using OpenCV."""
519
+ return cv2.imread(str(SOURCE))
520
+
521
+
522
+ @pytest.mark.parametrize(
523
+ "auto_augment, erasing, force_color_jitter",
524
+ [
525
+ (None, 0.0, False),
526
+ ("randaugment", 0.5, True),
527
+ ("augmix", 0.2, False),
528
+ ("autoaugment", 0.0, True),
529
+ ],
530
+ )
531
+ def test_classify_transforms_train(image, auto_augment, erasing, force_color_jitter):
532
+ """Tests classification transforms during training with various augmentations to ensure proper functionality."""
533
+ from ultralytics.data.augment import classify_augmentations
534
+
535
+ transform = classify_augmentations(
536
+ size=224,
537
+ mean=(0.5, 0.5, 0.5),
538
+ std=(0.5, 0.5, 0.5),
539
+ scale=(0.08, 1.0),
540
+ ratio=(3.0 / 4.0, 4.0 / 3.0),
541
+ hflip=0.5,
542
+ vflip=0.5,
543
+ auto_augment=auto_augment,
544
+ hsv_h=0.015,
545
+ hsv_s=0.4,
546
+ hsv_v=0.4,
547
+ force_color_jitter=force_color_jitter,
548
+ erasing=erasing,
549
+ )
550
+
551
+ transformed_image = transform(Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)))
552
+
553
+ assert transformed_image.shape == (3, 224, 224)
554
+ assert torch.is_tensor(transformed_image)
555
+ assert transformed_image.dtype == torch.float32
556
+
557
+
558
+ @pytest.mark.slow
559
+ @pytest.mark.skipif(not ONLINE, reason="environment is offline")
560
+ def test_model_tune():
561
+ """Tune YOLO model for performance improvement."""
562
+ YOLO("yolo11n-pose.pt").tune(data="coco8-pose.yaml", plots=False, imgsz=32, epochs=1, iterations=2, device="cpu")
563
+ YOLO("yolo11n-cls.pt").tune(data="imagenet10", plots=False, imgsz=32, epochs=1, iterations=2, device="cpu")
564
+
565
+
566
+ def test_model_embeddings():
567
+ """Test YOLO model embeddings."""
568
+ model_detect = YOLO(MODEL)
569
+ model_segment = YOLO(WEIGHTS_DIR / "yolo11n-seg.pt")
570
+
571
+ for batch in [SOURCE], [SOURCE, SOURCE]: # test batch size 1 and 2
572
+ assert len(model_detect.embed(source=batch, imgsz=32)) == len(batch)
573
+ assert len(model_segment.embed(source=batch, imgsz=32)) == len(batch)
574
+
575
+
576
+ @pytest.mark.skipif(checks.IS_PYTHON_3_12, reason="YOLOWorld with CLIP is not supported in Python 3.12")
577
+ def test_yolo_world():
578
+ """Tests YOLO world models with CLIP support, including detection and training scenarios."""
579
+ model = YOLO(WEIGHTS_DIR / "yolov8s-world.pt") # no YOLO11n-world model yet
580
+ model.set_classes(["tree", "window"])
581
+ model(SOURCE, conf=0.01)
582
+
583
+ model = YOLO(WEIGHTS_DIR / "yolov8s-worldv2.pt") # no YOLO11n-world model yet
584
+ # Training from a pretrained model. Eval is included at the final stage of training.
585
+ # Use dota8.yaml which has fewer categories to reduce the inference time of CLIP model
586
+ model.train(
587
+ data="dota8.yaml",
588
+ epochs=1,
589
+ imgsz=32,
590
+ cache="disk",
591
+ close_mosaic=1,
592
+ )
593
+
594
+ # test WorWorldTrainerFromScratch
595
+ from ultralytics.models.yolo.world.train_world import WorldTrainerFromScratch
596
+
597
+ model = YOLO("yolov8s-worldv2.yaml") # no YOLO11n-world model yet
598
+ model.train(
599
+ data={"train": {"yolo_data": ["dota8.yaml"]}, "val": {"yolo_data": ["dota8.yaml"]}},
600
+ epochs=1,
601
+ imgsz=32,
602
+ cache="disk",
603
+ close_mosaic=1,
604
+ trainer=WorldTrainerFromScratch,
605
+ )
606
+
607
+
608
+ def test_yolov10():
609
+ """Test YOLOv10 model training, validation, and prediction steps with minimal configurations."""
610
+ model = YOLO("yolov10n.yaml")
611
+ # train/val/predict
612
+ model.train(data="coco8.yaml", epochs=1, imgsz=32, close_mosaic=1, cache="disk")
613
+ model.val(data="coco8.yaml", imgsz=32)
614
+ model.predict(imgsz=32, save_txt=True, save_crop=True, augment=True)
615
+ model(SOURCE)