ultralytics-opencv-headless 8.3.246__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 (298) hide show
  1. tests/__init__.py +23 -0
  2. tests/conftest.py +59 -0
  3. tests/test_cli.py +131 -0
  4. tests/test_cuda.py +216 -0
  5. tests/test_engine.py +157 -0
  6. tests/test_exports.py +309 -0
  7. tests/test_integrations.py +151 -0
  8. tests/test_python.py +777 -0
  9. tests/test_solutions.py +371 -0
  10. ultralytics/__init__.py +48 -0
  11. ultralytics/assets/bus.jpg +0 -0
  12. ultralytics/assets/zidane.jpg +0 -0
  13. ultralytics/cfg/__init__.py +1026 -0
  14. ultralytics/cfg/datasets/Argoverse.yaml +78 -0
  15. ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
  16. ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
  17. ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
  18. ultralytics/cfg/datasets/HomeObjects-3K.yaml +32 -0
  19. ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
  20. ultralytics/cfg/datasets/Objects365.yaml +447 -0
  21. ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
  22. ultralytics/cfg/datasets/VOC.yaml +102 -0
  23. ultralytics/cfg/datasets/VisDrone.yaml +87 -0
  24. ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
  25. ultralytics/cfg/datasets/brain-tumor.yaml +22 -0
  26. ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
  27. ultralytics/cfg/datasets/coco-pose.yaml +64 -0
  28. ultralytics/cfg/datasets/coco.yaml +118 -0
  29. ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
  30. ultralytics/cfg/datasets/coco128.yaml +101 -0
  31. ultralytics/cfg/datasets/coco8-grayscale.yaml +103 -0
  32. ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
  33. ultralytics/cfg/datasets/coco8-pose.yaml +47 -0
  34. ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
  35. ultralytics/cfg/datasets/coco8.yaml +101 -0
  36. ultralytics/cfg/datasets/construction-ppe.yaml +32 -0
  37. ultralytics/cfg/datasets/crack-seg.yaml +22 -0
  38. ultralytics/cfg/datasets/dog-pose.yaml +52 -0
  39. ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
  40. ultralytics/cfg/datasets/dota8.yaml +35 -0
  41. ultralytics/cfg/datasets/hand-keypoints.yaml +50 -0
  42. ultralytics/cfg/datasets/kitti.yaml +27 -0
  43. ultralytics/cfg/datasets/lvis.yaml +1240 -0
  44. ultralytics/cfg/datasets/medical-pills.yaml +21 -0
  45. ultralytics/cfg/datasets/open-images-v7.yaml +663 -0
  46. ultralytics/cfg/datasets/package-seg.yaml +22 -0
  47. ultralytics/cfg/datasets/signature.yaml +21 -0
  48. ultralytics/cfg/datasets/tiger-pose.yaml +41 -0
  49. ultralytics/cfg/datasets/xView.yaml +155 -0
  50. ultralytics/cfg/default.yaml +130 -0
  51. ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
  52. ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
  53. ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
  54. ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
  55. ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
  56. ultralytics/cfg/models/11/yolo11.yaml +50 -0
  57. ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
  58. ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
  59. ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
  60. ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
  61. ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
  62. ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
  63. ultralytics/cfg/models/12/yolo12.yaml +48 -0
  64. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
  65. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
  66. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
  67. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
  68. ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
  69. ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
  70. ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
  71. ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
  72. ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
  73. ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
  74. ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
  75. ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
  76. ultralytics/cfg/models/v3/yolov3.yaml +49 -0
  77. ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
  78. ultralytics/cfg/models/v5/yolov5.yaml +51 -0
  79. ultralytics/cfg/models/v6/yolov6.yaml +56 -0
  80. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +48 -0
  81. ultralytics/cfg/models/v8/yoloe-v8.yaml +48 -0
  82. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
  83. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
  84. ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
  85. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
  86. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
  87. ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
  88. ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
  89. ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
  90. ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
  91. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
  92. ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
  93. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
  94. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
  95. ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
  96. ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
  97. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
  98. ultralytics/cfg/models/v8/yolov8.yaml +49 -0
  99. ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
  100. ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
  101. ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
  102. ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
  103. ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
  104. ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
  105. ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
  106. ultralytics/cfg/trackers/botsort.yaml +21 -0
  107. ultralytics/cfg/trackers/bytetrack.yaml +12 -0
  108. ultralytics/data/__init__.py +26 -0
  109. ultralytics/data/annotator.py +66 -0
  110. ultralytics/data/augment.py +2801 -0
  111. ultralytics/data/base.py +435 -0
  112. ultralytics/data/build.py +437 -0
  113. ultralytics/data/converter.py +855 -0
  114. ultralytics/data/dataset.py +834 -0
  115. ultralytics/data/loaders.py +704 -0
  116. ultralytics/data/scripts/download_weights.sh +18 -0
  117. ultralytics/data/scripts/get_coco.sh +61 -0
  118. ultralytics/data/scripts/get_coco128.sh +18 -0
  119. ultralytics/data/scripts/get_imagenet.sh +52 -0
  120. ultralytics/data/split.py +138 -0
  121. ultralytics/data/split_dota.py +344 -0
  122. ultralytics/data/utils.py +798 -0
  123. ultralytics/engine/__init__.py +1 -0
  124. ultralytics/engine/exporter.py +1578 -0
  125. ultralytics/engine/model.py +1124 -0
  126. ultralytics/engine/predictor.py +508 -0
  127. ultralytics/engine/results.py +1522 -0
  128. ultralytics/engine/trainer.py +974 -0
  129. ultralytics/engine/tuner.py +448 -0
  130. ultralytics/engine/validator.py +384 -0
  131. ultralytics/hub/__init__.py +166 -0
  132. ultralytics/hub/auth.py +151 -0
  133. ultralytics/hub/google/__init__.py +174 -0
  134. ultralytics/hub/session.py +422 -0
  135. ultralytics/hub/utils.py +162 -0
  136. ultralytics/models/__init__.py +9 -0
  137. ultralytics/models/fastsam/__init__.py +7 -0
  138. ultralytics/models/fastsam/model.py +79 -0
  139. ultralytics/models/fastsam/predict.py +169 -0
  140. ultralytics/models/fastsam/utils.py +23 -0
  141. ultralytics/models/fastsam/val.py +38 -0
  142. ultralytics/models/nas/__init__.py +7 -0
  143. ultralytics/models/nas/model.py +98 -0
  144. ultralytics/models/nas/predict.py +56 -0
  145. ultralytics/models/nas/val.py +38 -0
  146. ultralytics/models/rtdetr/__init__.py +7 -0
  147. ultralytics/models/rtdetr/model.py +63 -0
  148. ultralytics/models/rtdetr/predict.py +88 -0
  149. ultralytics/models/rtdetr/train.py +89 -0
  150. ultralytics/models/rtdetr/val.py +216 -0
  151. ultralytics/models/sam/__init__.py +25 -0
  152. ultralytics/models/sam/amg.py +275 -0
  153. ultralytics/models/sam/build.py +365 -0
  154. ultralytics/models/sam/build_sam3.py +377 -0
  155. ultralytics/models/sam/model.py +169 -0
  156. ultralytics/models/sam/modules/__init__.py +1 -0
  157. ultralytics/models/sam/modules/blocks.py +1067 -0
  158. ultralytics/models/sam/modules/decoders.py +495 -0
  159. ultralytics/models/sam/modules/encoders.py +794 -0
  160. ultralytics/models/sam/modules/memory_attention.py +298 -0
  161. ultralytics/models/sam/modules/sam.py +1160 -0
  162. ultralytics/models/sam/modules/tiny_encoder.py +979 -0
  163. ultralytics/models/sam/modules/transformer.py +344 -0
  164. ultralytics/models/sam/modules/utils.py +512 -0
  165. ultralytics/models/sam/predict.py +3940 -0
  166. ultralytics/models/sam/sam3/__init__.py +3 -0
  167. ultralytics/models/sam/sam3/decoder.py +546 -0
  168. ultralytics/models/sam/sam3/encoder.py +529 -0
  169. ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
  170. ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
  171. ultralytics/models/sam/sam3/model_misc.py +199 -0
  172. ultralytics/models/sam/sam3/necks.py +129 -0
  173. ultralytics/models/sam/sam3/sam3_image.py +339 -0
  174. ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
  175. ultralytics/models/sam/sam3/vitdet.py +547 -0
  176. ultralytics/models/sam/sam3/vl_combiner.py +160 -0
  177. ultralytics/models/utils/__init__.py +1 -0
  178. ultralytics/models/utils/loss.py +466 -0
  179. ultralytics/models/utils/ops.py +315 -0
  180. ultralytics/models/yolo/__init__.py +7 -0
  181. ultralytics/models/yolo/classify/__init__.py +7 -0
  182. ultralytics/models/yolo/classify/predict.py +90 -0
  183. ultralytics/models/yolo/classify/train.py +202 -0
  184. ultralytics/models/yolo/classify/val.py +216 -0
  185. ultralytics/models/yolo/detect/__init__.py +7 -0
  186. ultralytics/models/yolo/detect/predict.py +122 -0
  187. ultralytics/models/yolo/detect/train.py +227 -0
  188. ultralytics/models/yolo/detect/val.py +507 -0
  189. ultralytics/models/yolo/model.py +430 -0
  190. ultralytics/models/yolo/obb/__init__.py +7 -0
  191. ultralytics/models/yolo/obb/predict.py +56 -0
  192. ultralytics/models/yolo/obb/train.py +79 -0
  193. ultralytics/models/yolo/obb/val.py +302 -0
  194. ultralytics/models/yolo/pose/__init__.py +7 -0
  195. ultralytics/models/yolo/pose/predict.py +65 -0
  196. ultralytics/models/yolo/pose/train.py +110 -0
  197. ultralytics/models/yolo/pose/val.py +248 -0
  198. ultralytics/models/yolo/segment/__init__.py +7 -0
  199. ultralytics/models/yolo/segment/predict.py +109 -0
  200. ultralytics/models/yolo/segment/train.py +69 -0
  201. ultralytics/models/yolo/segment/val.py +307 -0
  202. ultralytics/models/yolo/world/__init__.py +5 -0
  203. ultralytics/models/yolo/world/train.py +173 -0
  204. ultralytics/models/yolo/world/train_world.py +178 -0
  205. ultralytics/models/yolo/yoloe/__init__.py +22 -0
  206. ultralytics/models/yolo/yoloe/predict.py +162 -0
  207. ultralytics/models/yolo/yoloe/train.py +287 -0
  208. ultralytics/models/yolo/yoloe/train_seg.py +122 -0
  209. ultralytics/models/yolo/yoloe/val.py +206 -0
  210. ultralytics/nn/__init__.py +27 -0
  211. ultralytics/nn/autobackend.py +958 -0
  212. ultralytics/nn/modules/__init__.py +182 -0
  213. ultralytics/nn/modules/activation.py +54 -0
  214. ultralytics/nn/modules/block.py +1947 -0
  215. ultralytics/nn/modules/conv.py +669 -0
  216. ultralytics/nn/modules/head.py +1183 -0
  217. ultralytics/nn/modules/transformer.py +793 -0
  218. ultralytics/nn/modules/utils.py +159 -0
  219. ultralytics/nn/tasks.py +1768 -0
  220. ultralytics/nn/text_model.py +356 -0
  221. ultralytics/py.typed +1 -0
  222. ultralytics/solutions/__init__.py +41 -0
  223. ultralytics/solutions/ai_gym.py +108 -0
  224. ultralytics/solutions/analytics.py +264 -0
  225. ultralytics/solutions/config.py +107 -0
  226. ultralytics/solutions/distance_calculation.py +123 -0
  227. ultralytics/solutions/heatmap.py +125 -0
  228. ultralytics/solutions/instance_segmentation.py +86 -0
  229. ultralytics/solutions/object_blurrer.py +89 -0
  230. ultralytics/solutions/object_counter.py +190 -0
  231. ultralytics/solutions/object_cropper.py +87 -0
  232. ultralytics/solutions/parking_management.py +280 -0
  233. ultralytics/solutions/queue_management.py +93 -0
  234. ultralytics/solutions/region_counter.py +133 -0
  235. ultralytics/solutions/security_alarm.py +151 -0
  236. ultralytics/solutions/similarity_search.py +219 -0
  237. ultralytics/solutions/solutions.py +828 -0
  238. ultralytics/solutions/speed_estimation.py +114 -0
  239. ultralytics/solutions/streamlit_inference.py +260 -0
  240. ultralytics/solutions/templates/similarity-search.html +156 -0
  241. ultralytics/solutions/trackzone.py +88 -0
  242. ultralytics/solutions/vision_eye.py +67 -0
  243. ultralytics/trackers/__init__.py +7 -0
  244. ultralytics/trackers/basetrack.py +115 -0
  245. ultralytics/trackers/bot_sort.py +257 -0
  246. ultralytics/trackers/byte_tracker.py +469 -0
  247. ultralytics/trackers/track.py +116 -0
  248. ultralytics/trackers/utils/__init__.py +1 -0
  249. ultralytics/trackers/utils/gmc.py +339 -0
  250. ultralytics/trackers/utils/kalman_filter.py +482 -0
  251. ultralytics/trackers/utils/matching.py +154 -0
  252. ultralytics/utils/__init__.py +1450 -0
  253. ultralytics/utils/autobatch.py +118 -0
  254. ultralytics/utils/autodevice.py +205 -0
  255. ultralytics/utils/benchmarks.py +728 -0
  256. ultralytics/utils/callbacks/__init__.py +5 -0
  257. ultralytics/utils/callbacks/base.py +233 -0
  258. ultralytics/utils/callbacks/clearml.py +146 -0
  259. ultralytics/utils/callbacks/comet.py +625 -0
  260. ultralytics/utils/callbacks/dvc.py +197 -0
  261. ultralytics/utils/callbacks/hub.py +110 -0
  262. ultralytics/utils/callbacks/mlflow.py +134 -0
  263. ultralytics/utils/callbacks/neptune.py +126 -0
  264. ultralytics/utils/callbacks/platform.py +313 -0
  265. ultralytics/utils/callbacks/raytune.py +42 -0
  266. ultralytics/utils/callbacks/tensorboard.py +123 -0
  267. ultralytics/utils/callbacks/wb.py +188 -0
  268. ultralytics/utils/checks.py +1006 -0
  269. ultralytics/utils/cpu.py +85 -0
  270. ultralytics/utils/dist.py +123 -0
  271. ultralytics/utils/downloads.py +529 -0
  272. ultralytics/utils/errors.py +35 -0
  273. ultralytics/utils/events.py +113 -0
  274. ultralytics/utils/export/__init__.py +7 -0
  275. ultralytics/utils/export/engine.py +237 -0
  276. ultralytics/utils/export/imx.py +315 -0
  277. ultralytics/utils/export/tensorflow.py +231 -0
  278. ultralytics/utils/files.py +219 -0
  279. ultralytics/utils/git.py +137 -0
  280. ultralytics/utils/instance.py +484 -0
  281. ultralytics/utils/logger.py +501 -0
  282. ultralytics/utils/loss.py +849 -0
  283. ultralytics/utils/metrics.py +1563 -0
  284. ultralytics/utils/nms.py +337 -0
  285. ultralytics/utils/ops.py +664 -0
  286. ultralytics/utils/patches.py +201 -0
  287. ultralytics/utils/plotting.py +1045 -0
  288. ultralytics/utils/tal.py +403 -0
  289. ultralytics/utils/torch_utils.py +984 -0
  290. ultralytics/utils/tqdm.py +440 -0
  291. ultralytics/utils/triton.py +112 -0
  292. ultralytics/utils/tuner.py +160 -0
  293. ultralytics_opencv_headless-8.3.246.dist-info/METADATA +374 -0
  294. ultralytics_opencv_headless-8.3.246.dist-info/RECORD +298 -0
  295. ultralytics_opencv_headless-8.3.246.dist-info/WHEEL +5 -0
  296. ultralytics_opencv_headless-8.3.246.dist-info/entry_points.txt +3 -0
  297. ultralytics_opencv_headless-8.3.246.dist-info/licenses/LICENSE +661 -0
  298. ultralytics_opencv_headless-8.3.246.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1006 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import functools
7
+ import glob
8
+ import inspect
9
+ import math
10
+ import os
11
+ import platform
12
+ import re
13
+ import shutil
14
+ import subprocess
15
+ import time
16
+ from importlib import metadata
17
+ from pathlib import Path
18
+ from types import SimpleNamespace
19
+
20
+ import cv2
21
+ import numpy as np
22
+ import torch
23
+
24
+ from ultralytics.utils import (
25
+ ARM64,
26
+ ASSETS,
27
+ ASSETS_URL,
28
+ AUTOINSTALL,
29
+ GIT,
30
+ IS_COLAB,
31
+ IS_JETSON,
32
+ IS_KAGGLE,
33
+ IS_PIP_PACKAGE,
34
+ LINUX,
35
+ LOGGER,
36
+ MACOS,
37
+ ONLINE,
38
+ PYTHON_VERSION,
39
+ RKNN_CHIPS,
40
+ ROOT,
41
+ TORCH_VERSION,
42
+ TORCHVISION_VERSION,
43
+ USER_CONFIG_DIR,
44
+ WINDOWS,
45
+ Retry,
46
+ ThreadingLocked,
47
+ TryExcept,
48
+ clean_url,
49
+ colorstr,
50
+ downloads,
51
+ is_github_action_running,
52
+ url2file,
53
+ )
54
+
55
+
56
+ def parse_requirements(file_path=ROOT.parent / "requirements.txt", package=""):
57
+ """Parse a requirements.txt file, ignoring lines that start with '#' and any text after '#'.
58
+
59
+ Args:
60
+ file_path (Path): Path to the requirements.txt file.
61
+ package (str, optional): Python package to use instead of requirements.txt file.
62
+
63
+ Returns:
64
+ requirements (list[SimpleNamespace]): List of parsed requirements as SimpleNamespace objects with `name` and
65
+ `specifier` attributes.
66
+
67
+ Examples:
68
+ >>> from ultralytics.utils.checks import parse_requirements
69
+ >>> parse_requirements(package="ultralytics")
70
+ """
71
+ if package:
72
+ requires = [x for x in metadata.distribution(package).requires if "extra == " not in x]
73
+ else:
74
+ requires = Path(file_path).read_text().splitlines()
75
+
76
+ requirements = []
77
+ for line in requires:
78
+ line = line.strip()
79
+ if line and not line.startswith("#"):
80
+ line = line.partition("#")[0].strip() # ignore inline comments
81
+ if match := re.match(r"([a-zA-Z0-9-_]+)\s*([<>!=~]+.*)?", line):
82
+ requirements.append(SimpleNamespace(name=match[1], specifier=match[2].strip() if match[2] else ""))
83
+
84
+ return requirements
85
+
86
+
87
+ @functools.lru_cache
88
+ def parse_version(version="0.0.0") -> tuple:
89
+ """Convert a version string to a tuple of integers, ignoring any extra non-numeric string attached to the version.
90
+
91
+ Args:
92
+ version (str): Version string, i.e. '2.0.1+cpu'
93
+
94
+ Returns:
95
+ (tuple): Tuple of integers representing the numeric part of the version, i.e. (2, 0, 1)
96
+ """
97
+ try:
98
+ return tuple(map(int, re.findall(r"\d+", version)[:3])) # '2.0.1+cpu' -> (2, 0, 1)
99
+ except Exception as e:
100
+ LOGGER.warning(f"failure for parse_version({version}), returning (0, 0, 0): {e}")
101
+ return 0, 0, 0
102
+
103
+
104
+ def is_ascii(s) -> bool:
105
+ """Check if a string is composed of only ASCII characters.
106
+
107
+ Args:
108
+ s (str | list | tuple | dict): Input to be checked (all are converted to string for checking).
109
+
110
+ Returns:
111
+ (bool): True if the string is composed only of ASCII characters, False otherwise.
112
+ """
113
+ return all(ord(c) < 128 for c in str(s))
114
+
115
+
116
+ def check_imgsz(imgsz, stride=32, min_dim=1, max_dim=2, floor=0):
117
+ """Verify image size is a multiple of the given stride in each dimension. If the image size is not a multiple of the
118
+ stride, update it to the nearest multiple of the stride that is greater than or equal to the given floor value.
119
+
120
+ Args:
121
+ imgsz (int | list[int]): Image size.
122
+ stride (int): Stride value.
123
+ min_dim (int): Minimum number of dimensions.
124
+ max_dim (int): Maximum number of dimensions.
125
+ floor (int): Minimum allowed value for image size.
126
+
127
+ Returns:
128
+ (list[int] | int): Updated image size.
129
+ """
130
+ # Convert stride to integer if it is a tensor
131
+ stride = int(stride.max() if isinstance(stride, torch.Tensor) else stride)
132
+
133
+ # Convert image size to list if it is an integer
134
+ if isinstance(imgsz, int):
135
+ imgsz = [imgsz]
136
+ elif isinstance(imgsz, (list, tuple)):
137
+ imgsz = list(imgsz)
138
+ elif isinstance(imgsz, str): # i.e. '640' or '[640,640]'
139
+ imgsz = [int(imgsz)] if imgsz.isnumeric() else ast.literal_eval(imgsz)
140
+ else:
141
+ raise TypeError(
142
+ f"'imgsz={imgsz}' is of invalid type {type(imgsz).__name__}. "
143
+ f"Valid imgsz types are int i.e. 'imgsz=640' or list i.e. 'imgsz=[640,640]'"
144
+ )
145
+
146
+ # Apply max_dim
147
+ if len(imgsz) > max_dim:
148
+ msg = (
149
+ "'train' and 'val' imgsz must be an integer, while 'predict' and 'export' imgsz may be a [h, w] list "
150
+ "or an integer, i.e. 'yolo export imgsz=640,480' or 'yolo export imgsz=640'"
151
+ )
152
+ if max_dim != 1:
153
+ raise ValueError(f"imgsz={imgsz} is not a valid image size. {msg}")
154
+ LOGGER.warning(f"updating to 'imgsz={max(imgsz)}'. {msg}")
155
+ imgsz = [max(imgsz)]
156
+ # Make image size a multiple of the stride
157
+ sz = [max(math.ceil(x / stride) * stride, floor) for x in imgsz]
158
+
159
+ # Print warning message if image size was updated
160
+ if sz != imgsz:
161
+ LOGGER.warning(f"imgsz={imgsz} must be multiple of max stride {stride}, updating to {sz}")
162
+
163
+ # Add missing dimensions if necessary
164
+ sz = [sz[0], sz[0]] if min_dim == 2 and len(sz) == 1 else sz[0] if min_dim == 1 and len(sz) == 1 else sz
165
+
166
+ return sz
167
+
168
+
169
+ @functools.lru_cache
170
+ def check_uv():
171
+ """Check if uv package manager is installed and can run successfully."""
172
+ try:
173
+ return subprocess.run(["uv", "-V"], capture_output=True).returncode == 0
174
+ except FileNotFoundError:
175
+ return False
176
+
177
+
178
+ @functools.lru_cache
179
+ def check_version(
180
+ current: str = "0.0.0",
181
+ required: str = "0.0.0",
182
+ name: str = "version",
183
+ hard: bool = False,
184
+ verbose: bool = False,
185
+ msg: str = "",
186
+ ) -> bool:
187
+ """Check current version against the required version or range.
188
+
189
+ Args:
190
+ current (str): Current version or package name to get version from.
191
+ required (str): Required version or range (in pip-style format).
192
+ name (str): Name to be used in warning message.
193
+ hard (bool): If True, raise an AssertionError if the requirement is not met.
194
+ verbose (bool): If True, print warning message if requirement is not met.
195
+ msg (str): Extra message to display if verbose.
196
+
197
+ Returns:
198
+ (bool): True if requirement is met, False otherwise.
199
+
200
+ Examples:
201
+ Check if current version is exactly 22.04
202
+ >>> check_version(current="22.04", required="==22.04")
203
+
204
+ Check if current version is greater than or equal to 22.04
205
+ >>> check_version(current="22.10", required="22.04") # assumes '>=' inequality if none passed
206
+
207
+ Check if current version is less than or equal to 22.04
208
+ >>> check_version(current="22.04", required="<=22.04")
209
+
210
+ Check if current version is between 20.04 (inclusive) and 22.04 (exclusive)
211
+ >>> check_version(current="21.10", required=">20.04,<22.04")
212
+ """
213
+ if not current: # if current is '' or None
214
+ LOGGER.warning(f"invalid check_version({current}, {required}) requested, please check values.")
215
+ return True
216
+ elif not current[0].isdigit(): # current is package name rather than version string, i.e. current='ultralytics'
217
+ try:
218
+ name = current # assigned package name to 'name' arg
219
+ current = metadata.version(current) # get version string from package name
220
+ except metadata.PackageNotFoundError as e:
221
+ if hard:
222
+ raise ModuleNotFoundError(f"{current} package is required but not installed") from e
223
+ else:
224
+ return False
225
+
226
+ if not required: # if required is '' or None
227
+ return True
228
+
229
+ if "sys_platform" in required and ( # i.e. required='<2.4.0,>=1.8.0; sys_platform == "win32"'
230
+ (WINDOWS and "win32" not in required)
231
+ or (LINUX and "linux" not in required)
232
+ or (MACOS and "macos" not in required and "darwin" not in required)
233
+ ):
234
+ return True
235
+
236
+ op = ""
237
+ version = ""
238
+ result = True
239
+ c = parse_version(current) # '1.2.3' -> (1, 2, 3)
240
+ for r in required.strip(",").split(","):
241
+ op, version = re.match(r"([^0-9]*)([\d.]+)", r).groups() # split '>=22.04' -> ('>=', '22.04')
242
+ if not op:
243
+ op = ">=" # assume >= if no op passed
244
+ v = parse_version(version) # '1.2.3' -> (1, 2, 3)
245
+ if op == "==" and c != v:
246
+ result = False
247
+ elif op == "!=" and c == v:
248
+ result = False
249
+ elif op == ">=" and not (c >= v):
250
+ result = False
251
+ elif op == "<=" and not (c <= v):
252
+ result = False
253
+ elif op == ">" and not (c > v):
254
+ result = False
255
+ elif op == "<" and not (c < v):
256
+ result = False
257
+ if not result:
258
+ warning = f"{name}{required} is required, but {name}=={current} is currently installed {msg}"
259
+ if hard:
260
+ raise ModuleNotFoundError(warning) # assert version requirements met
261
+ if verbose:
262
+ LOGGER.warning(warning)
263
+ return result
264
+
265
+
266
+ def check_latest_pypi_version(package_name="ultralytics"):
267
+ """Return the latest version of a PyPI package without downloading or installing it.
268
+
269
+ Args:
270
+ package_name (str): The name of the package to find the latest version for.
271
+
272
+ Returns:
273
+ (str): The latest version of the package.
274
+ """
275
+ import requests # scoped as slow import
276
+
277
+ try:
278
+ requests.packages.urllib3.disable_warnings() # Disable the InsecureRequestWarning
279
+ response = requests.get(f"https://pypi.org/pypi/{package_name}/json", timeout=3)
280
+ if response.status_code == 200:
281
+ return response.json()["info"]["version"]
282
+ except Exception:
283
+ return None
284
+
285
+
286
+ def check_pip_update_available():
287
+ """Check if a new version of the ultralytics package is available on PyPI.
288
+
289
+ Returns:
290
+ (bool): True if an update is available, False otherwise.
291
+ """
292
+ if ONLINE and IS_PIP_PACKAGE:
293
+ try:
294
+ from ultralytics import __version__
295
+
296
+ latest = check_latest_pypi_version()
297
+ if check_version(__version__, f"<{latest}"): # check if current version is < latest version
298
+ LOGGER.info(
299
+ f"New https://pypi.org/project/ultralytics/{latest} available 😃 "
300
+ f"Update with 'pip install -U ultralytics'"
301
+ )
302
+ return True
303
+ except Exception:
304
+ pass
305
+ return False
306
+
307
+
308
+ @ThreadingLocked()
309
+ @functools.lru_cache
310
+ def check_font(font="Arial.ttf"):
311
+ """Find font locally or download to user's configuration directory if it does not already exist.
312
+
313
+ Args:
314
+ font (str): Path or name of font.
315
+
316
+ Returns:
317
+ (Path): Resolved font file path.
318
+ """
319
+ from matplotlib import font_manager # scope for faster 'import ultralytics'
320
+
321
+ # Check USER_CONFIG_DIR
322
+ name = Path(font).name
323
+ file = USER_CONFIG_DIR / name
324
+ if file.exists():
325
+ return file
326
+
327
+ # Check system fonts
328
+ matches = [s for s in font_manager.findSystemFonts() if font in s]
329
+ if any(matches):
330
+ return matches[0]
331
+
332
+ # Download to USER_CONFIG_DIR if missing
333
+ url = f"{ASSETS_URL}/{name}"
334
+ if downloads.is_url(url, check=True):
335
+ downloads.safe_download(url=url, file=file)
336
+ return file
337
+
338
+
339
+ def check_python(minimum: str = "3.8.0", hard: bool = True, verbose: bool = False) -> bool:
340
+ """Check current python version against the required minimum version.
341
+
342
+ Args:
343
+ minimum (str): Required minimum version of python.
344
+ hard (bool): If True, raise an AssertionError if the requirement is not met.
345
+ verbose (bool): If True, print warning message if requirement is not met.
346
+
347
+ Returns:
348
+ (bool): Whether the installed Python version meets the minimum constraints.
349
+ """
350
+ return check_version(PYTHON_VERSION, minimum, name="Python", hard=hard, verbose=verbose)
351
+
352
+
353
+ @TryExcept()
354
+ def check_apt_requirements(requirements):
355
+ """Check if apt packages are installed and install missing ones.
356
+
357
+ Args:
358
+ requirements: List of apt package names to check and install
359
+ """
360
+ prefix = colorstr("red", "bold", "apt requirements:")
361
+ # Check which packages are missing
362
+ missing_packages = []
363
+ for package in requirements:
364
+ try:
365
+ # Use dpkg -l to check if package is installed
366
+ result = subprocess.run(["dpkg", "-l", package], capture_output=True, text=True, check=False)
367
+ # Check if package is installed (look for "ii" status)
368
+ if result.returncode != 0 or not any(
369
+ line.startswith("ii") and package in line for line in result.stdout.splitlines()
370
+ ):
371
+ missing_packages.append(package)
372
+ except Exception:
373
+ # If check fails, assume package is not installed
374
+ missing_packages.append(package)
375
+
376
+ # Install missing packages if any
377
+ if missing_packages:
378
+ LOGGER.info(
379
+ f"{prefix} Ultralytics requirement{'s' * (len(missing_packages) > 1)} {missing_packages} not found, attempting AutoUpdate..."
380
+ )
381
+ # Optionally update package list first
382
+ cmd = (["sudo"] if is_sudo_available() else []) + ["apt", "update"]
383
+ result = subprocess.run(cmd, check=True, capture_output=True, text=True)
384
+
385
+ # Build and run the install command
386
+ cmd = (["sudo"] if is_sudo_available() else []) + ["apt", "install", "-y"] + missing_packages
387
+ result = subprocess.run(cmd, check=True, capture_output=True, text=True)
388
+
389
+ LOGGER.info(f"{prefix} AutoUpdate success ✅")
390
+ LOGGER.warning(f"{prefix} {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n")
391
+
392
+
393
+ @TryExcept()
394
+ def check_requirements(requirements=ROOT.parent / "requirements.txt", exclude=(), install=True, cmds=""):
395
+ """Check if installed dependencies meet Ultralytics YOLO models requirements and attempt to auto-update if needed.
396
+
397
+ Args:
398
+ requirements (Path | str | list[str|tuple] | tuple[str]): Path to a requirements.txt file, a single package
399
+ requirement as a string, a list of package requirements as strings, or a list containing strings and tuples
400
+ of interchangeable packages.
401
+ exclude (tuple): Tuple of package names to exclude from checking.
402
+ install (bool): If True, attempt to auto-update packages that don't meet requirements.
403
+ cmds (str): Additional commands to pass to the pip install command when auto-updating.
404
+
405
+ Examples:
406
+ >>> from ultralytics.utils.checks import check_requirements
407
+
408
+ Check a requirements.txt file
409
+ >>> check_requirements("path/to/requirements.txt")
410
+
411
+ Check a single package
412
+ >>> check_requirements("ultralytics>=8.3.200", cmds="--index-url https://download.pytorch.org/whl/cpu")
413
+
414
+ Check multiple packages
415
+ >>> check_requirements(["numpy", "ultralytics"])
416
+
417
+ Check with interchangeable packages
418
+ >>> check_requirements([("onnxruntime", "onnxruntime-gpu"), "numpy"])
419
+ """
420
+ prefix = colorstr("red", "bold", "requirements:")
421
+
422
+ if os.environ.get("ULTRALYTICS_SKIP_REQUIREMENTS_CHECKS", "0") == "1":
423
+ LOGGER.info(f"{prefix} ULTRALYTICS_SKIP_REQUIREMENTS_CHECKS=1 detected, skipping requirements check.")
424
+ return True
425
+
426
+ if isinstance(requirements, Path): # requirements.txt file
427
+ file = requirements.resolve()
428
+ assert file.exists(), f"{prefix} {file} not found, check failed."
429
+ requirements = [f"{x.name}{x.specifier}" for x in parse_requirements(file) if x.name not in exclude]
430
+ elif isinstance(requirements, str):
431
+ requirements = [requirements]
432
+
433
+ pkgs = []
434
+ for r in requirements:
435
+ candidates = r if isinstance(r, (list, tuple)) else [r]
436
+ satisfied = False
437
+
438
+ for candidate in candidates:
439
+ r_stripped = candidate.rpartition("/")[-1].replace(".git", "") # replace git+https://org/repo.git -> 'repo'
440
+ match = re.match(r"([a-zA-Z0-9-_]+)([<>!=~]+.*)?", r_stripped)
441
+ name, required = match[1], match[2].strip() if match[2] else ""
442
+ try:
443
+ if check_version(metadata.version(name), required):
444
+ satisfied = True
445
+ break
446
+ except (AssertionError, metadata.PackageNotFoundError):
447
+ continue
448
+
449
+ if not satisfied:
450
+ pkgs.append(candidates[0])
451
+
452
+ @Retry(times=2, delay=1)
453
+ def attempt_install(packages, commands, use_uv):
454
+ """Attempt package installation with uv if available, falling back to pip."""
455
+ if use_uv:
456
+ base = (
457
+ f"uv pip install --no-cache-dir {packages} {commands} "
458
+ f"--index-strategy=unsafe-best-match --break-system-packages"
459
+ )
460
+ try:
461
+ return subprocess.check_output(base, shell=True, stderr=subprocess.STDOUT, text=True)
462
+ except subprocess.CalledProcessError as e:
463
+ if e.output and "No virtual environment found" in e.output:
464
+ return subprocess.check_output(
465
+ base.replace("uv pip install", "uv pip install --system"),
466
+ shell=True,
467
+ stderr=subprocess.STDOUT,
468
+ text=True,
469
+ )
470
+ raise
471
+ return subprocess.check_output(
472
+ f"pip install --no-cache-dir {packages} {commands}", shell=True, stderr=subprocess.STDOUT, text=True
473
+ )
474
+
475
+ s = " ".join(f'"{x}"' for x in pkgs) # console string
476
+ if s:
477
+ if install and AUTOINSTALL: # check environment variable
478
+ # Note uv fails on arm64 macOS and Raspberry Pi runners
479
+ n = len(pkgs) # number of packages updates
480
+ LOGGER.info(f"{prefix} Ultralytics requirement{'s' * (n > 1)} {pkgs} not found, attempting AutoUpdate...")
481
+ try:
482
+ t = time.time()
483
+ assert ONLINE, "AutoUpdate skipped (offline)"
484
+ use_uv = not ARM64 and check_uv() # uv fails on ARM64
485
+ LOGGER.info(attempt_install(s, cmds, use_uv=use_uv))
486
+ dt = time.time() - t
487
+ LOGGER.info(f"{prefix} AutoUpdate success ✅ {dt:.1f}s")
488
+ LOGGER.warning(
489
+ f"{prefix} {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n"
490
+ )
491
+ except Exception as e:
492
+ msg = f"{prefix} ❌ {e}"
493
+ if hasattr(e, "output") and e.output:
494
+ msg += f"\n{e.output}"
495
+ LOGGER.warning(msg)
496
+ return False
497
+ else:
498
+ return False
499
+
500
+ return True
501
+
502
+
503
+ def check_torchvision():
504
+ """Check the installed versions of PyTorch and Torchvision to ensure they're compatible.
505
+
506
+ This function checks the installed versions of PyTorch and Torchvision, and warns if they're incompatible according
507
+ to the compatibility table based on: https://github.com/pytorch/vision#installation.
508
+ """
509
+ compatibility_table = {
510
+ "2.9": ["0.24"],
511
+ "2.8": ["0.23"],
512
+ "2.7": ["0.22"],
513
+ "2.6": ["0.21"],
514
+ "2.5": ["0.20"],
515
+ "2.4": ["0.19"],
516
+ "2.3": ["0.18"],
517
+ "2.2": ["0.17"],
518
+ "2.1": ["0.16"],
519
+ "2.0": ["0.15"],
520
+ "1.13": ["0.14"],
521
+ "1.12": ["0.13"],
522
+ }
523
+
524
+ # Check major and minor versions
525
+ v_torch = ".".join(TORCH_VERSION.split("+", 1)[0].split(".")[:2])
526
+ if v_torch in compatibility_table:
527
+ compatible_versions = compatibility_table[v_torch]
528
+ v_torchvision = ".".join(TORCHVISION_VERSION.split("+", 1)[0].split(".")[:2])
529
+ if all(v_torchvision != v for v in compatible_versions):
530
+ LOGGER.warning(
531
+ f"torchvision=={v_torchvision} is incompatible with torch=={v_torch}.\n"
532
+ f"Run 'pip install torchvision=={compatible_versions[0]}' to fix torchvision or "
533
+ "'pip install -U torch torchvision' to update both.\n"
534
+ "For a full compatibility table see https://github.com/pytorch/vision#installation"
535
+ )
536
+
537
+
538
+ def check_suffix(file="yolo11n.pt", suffix=".pt", msg=""):
539
+ """Check file(s) for acceptable suffix.
540
+
541
+ Args:
542
+ file (str | list[str]): File or list of files to check.
543
+ suffix (str | tuple): Acceptable suffix or tuple of suffixes.
544
+ msg (str): Additional message to display in case of error.
545
+ """
546
+ if file and suffix:
547
+ if isinstance(suffix, str):
548
+ suffix = {suffix}
549
+ for f in file if isinstance(file, (list, tuple)) else [file]:
550
+ if s := str(f).rpartition(".")[-1].lower().strip(): # file suffix
551
+ assert f".{s}" in suffix, f"{msg}{f} acceptable suffix is {suffix}, not .{s}"
552
+
553
+
554
+ def check_yolov5u_filename(file: str, verbose: bool = True):
555
+ """Replace legacy YOLOv5 filenames with updated YOLOv5u filenames.
556
+
557
+ Args:
558
+ file (str): Filename to check and potentially update.
559
+ verbose (bool): Whether to print information about the replacement.
560
+
561
+ Returns:
562
+ (str): Updated filename.
563
+ """
564
+ if "yolov3" in file or "yolov5" in file:
565
+ if "u.yaml" in file:
566
+ file = file.replace("u.yaml", ".yaml") # i.e. yolov5nu.yaml -> yolov5n.yaml
567
+ elif ".pt" in file and "u" not in file:
568
+ original_file = file
569
+ file = re.sub(r"(.*yolov5([nsmlx]))\.pt", "\\1u.pt", file) # i.e. yolov5n.pt -> yolov5nu.pt
570
+ file = re.sub(r"(.*yolov5([nsmlx])6)\.pt", "\\1u.pt", file) # i.e. yolov5n6.pt -> yolov5n6u.pt
571
+ file = re.sub(r"(.*yolov3(|-tiny|-spp))\.pt", "\\1u.pt", file) # i.e. yolov3-spp.pt -> yolov3-sppu.pt
572
+ if file != original_file and verbose:
573
+ LOGGER.info(
574
+ f"PRO TIP 💡 Replace 'model={original_file}' with new 'model={file}'.\nYOLOv5 'u' models are "
575
+ f"trained with https://github.com/ultralytics/ultralytics and feature improved performance vs "
576
+ f"standard YOLOv5 models trained with https://github.com/ultralytics/yolov5.\n"
577
+ )
578
+ return file
579
+
580
+
581
+ def check_model_file_from_stem(model="yolo11n"):
582
+ """Return a model filename from a valid model stem.
583
+
584
+ Args:
585
+ model (str): Model stem to check.
586
+
587
+ Returns:
588
+ (str | Path): Model filename with appropriate suffix.
589
+ """
590
+ path = Path(model)
591
+ if not path.suffix and path.stem in downloads.GITHUB_ASSETS_STEMS:
592
+ return path.with_suffix(".pt") # add suffix, i.e. yolo11n -> yolo11n.pt
593
+ return model
594
+
595
+
596
+ def check_file(file, suffix="", download=True, download_dir=".", hard=True):
597
+ """Search/download file (if necessary), check suffix (if provided), and return path.
598
+
599
+ Args:
600
+ file (str): File name or path.
601
+ suffix (str | tuple): Acceptable suffix or tuple of suffixes to validate against the file.
602
+ download (bool): Whether to download the file if it doesn't exist locally.
603
+ download_dir (str): Directory to download the file to.
604
+ hard (bool): Whether to raise an error if the file is not found.
605
+
606
+ Returns:
607
+ (str): Path to the file.
608
+ """
609
+ check_suffix(file, suffix) # optional
610
+ file = str(file).strip() # convert to string and strip spaces
611
+ file = check_yolov5u_filename(file) # yolov5n -> yolov5nu
612
+ if (
613
+ not file
614
+ or ("://" not in file and Path(file).exists()) # '://' check required in Windows Python<3.10
615
+ or file.lower().startswith("grpc://")
616
+ ): # file exists or gRPC Triton images
617
+ return file
618
+ elif download and file.lower().startswith(("https://", "http://", "rtsp://", "rtmp://", "tcp://")): # download
619
+ url = file # warning: Pathlib turns :// -> :/
620
+ file = Path(download_dir) / url2file(file) # '%2F' to '/', split https://url.com/file.txt?auth
621
+ if file.exists():
622
+ LOGGER.info(f"Found {clean_url(url)} locally at {file}") # file already exists
623
+ else:
624
+ downloads.safe_download(url=url, file=file, unzip=False)
625
+ return str(file)
626
+ else: # search
627
+ files = glob.glob(str(ROOT / "**" / file), recursive=True) or glob.glob(str(ROOT.parent / file)) # find file
628
+ if not files and hard:
629
+ raise FileNotFoundError(f"'{file}' does not exist")
630
+ elif len(files) > 1 and hard:
631
+ raise FileNotFoundError(f"Multiple files match '{file}', specify exact path: {files}")
632
+ return files[0] if len(files) else [] # return file
633
+
634
+
635
+ def check_yaml(file, suffix=(".yaml", ".yml"), hard=True):
636
+ """Search/download YAML file (if necessary) and return path, checking suffix.
637
+
638
+ Args:
639
+ file (str | Path): File name or path.
640
+ suffix (tuple): Tuple of acceptable YAML file suffixes.
641
+ hard (bool): Whether to raise an error if the file is not found or multiple files are found.
642
+
643
+ Returns:
644
+ (str): Path to the YAML file.
645
+ """
646
+ return check_file(file, suffix, hard=hard)
647
+
648
+
649
+ def check_is_path_safe(basedir, path):
650
+ """Check if the resolved path is under the intended directory to prevent path traversal.
651
+
652
+ Args:
653
+ basedir (Path | str): The intended directory.
654
+ path (Path | str): The path to check.
655
+
656
+ Returns:
657
+ (bool): True if the path is safe, False otherwise.
658
+ """
659
+ base_dir_resolved = Path(basedir).resolve()
660
+ path_resolved = Path(path).resolve()
661
+
662
+ return path_resolved.exists() and path_resolved.parts[: len(base_dir_resolved.parts)] == base_dir_resolved.parts
663
+
664
+
665
+ @functools.lru_cache
666
+ def check_imshow(warn=False):
667
+ """Check if environment supports image displays.
668
+
669
+ Args:
670
+ warn (bool): Whether to warn if environment doesn't support image displays.
671
+
672
+ Returns:
673
+ (bool): True if environment supports image displays, False otherwise.
674
+ """
675
+ try:
676
+ if LINUX:
677
+ assert not IS_COLAB and not IS_KAGGLE
678
+ assert "DISPLAY" in os.environ, "The DISPLAY environment variable isn't set."
679
+ cv2.imshow("test", np.zeros((8, 8, 3), dtype=np.uint8)) # show a small 8-pixel image
680
+ cv2.waitKey(1)
681
+ cv2.destroyAllWindows()
682
+ cv2.waitKey(1)
683
+ return True
684
+ except Exception as e:
685
+ if warn:
686
+ LOGGER.warning(f"Environment does not support cv2.imshow() or PIL Image.show()\n{e}")
687
+ return False
688
+
689
+
690
+ def check_yolo(verbose=True, device=""):
691
+ """Return a human-readable YOLO software and hardware summary.
692
+
693
+ Args:
694
+ verbose (bool): Whether to print verbose information.
695
+ device (str | torch.device): Device to use for YOLO.
696
+ """
697
+ import psutil # scoped as slow import
698
+
699
+ from ultralytics.utils.torch_utils import select_device
700
+
701
+ if IS_COLAB:
702
+ shutil.rmtree("sample_data", ignore_errors=True) # remove colab /sample_data directory
703
+
704
+ if verbose:
705
+ # System info
706
+ gib = 1 << 30 # bytes per GiB
707
+ ram = psutil.virtual_memory().total
708
+ total, _used, free = shutil.disk_usage("/")
709
+ s = f"({os.cpu_count()} CPUs, {ram / gib:.1f} GB RAM, {(total - free) / gib:.1f}/{total / gib:.1f} GB disk)"
710
+ try:
711
+ from IPython import display
712
+
713
+ display.clear_output() # clear display if notebook
714
+ except ImportError:
715
+ pass
716
+ else:
717
+ s = ""
718
+
719
+ if GIT.is_repo:
720
+ check_multiple_install() # check conflicting installation if using local clone
721
+
722
+ select_device(device=device, newline=False)
723
+ LOGGER.info(f"Setup complete ✅ {s}")
724
+
725
+
726
+ def collect_system_info():
727
+ """Collect and print relevant system information including OS, Python, RAM, CPU, and CUDA.
728
+
729
+ Returns:
730
+ (dict): Dictionary containing system information.
731
+ """
732
+ import psutil # scoped as slow import
733
+
734
+ from ultralytics.utils import ENVIRONMENT # scope to avoid circular import
735
+ from ultralytics.utils.torch_utils import get_cpu_info, get_gpu_info
736
+
737
+ gib = 1 << 30 # bytes per GiB
738
+ cuda = torch.cuda.is_available()
739
+ check_yolo()
740
+ total, _used, free = shutil.disk_usage("/")
741
+
742
+ info_dict = {
743
+ "OS": platform.platform(),
744
+ "Environment": ENVIRONMENT,
745
+ "Python": PYTHON_VERSION,
746
+ "Install": "git" if GIT.is_repo else "pip" if IS_PIP_PACKAGE else "other",
747
+ "Path": str(ROOT),
748
+ "RAM": f"{psutil.virtual_memory().total / gib:.2f} GB",
749
+ "Disk": f"{(total - free) / gib:.1f}/{total / gib:.1f} GB",
750
+ "CPU": get_cpu_info(),
751
+ "CPU count": os.cpu_count(),
752
+ "GPU": get_gpu_info(index=0) if cuda else None,
753
+ "GPU count": torch.cuda.device_count() if cuda else None,
754
+ "CUDA": torch.version.cuda if cuda else None,
755
+ }
756
+ LOGGER.info("\n" + "\n".join(f"{k:<23}{v}" for k, v in info_dict.items()) + "\n")
757
+
758
+ package_info = {}
759
+ for r in parse_requirements(package="ultralytics"):
760
+ try:
761
+ current = metadata.version(r.name)
762
+ is_met = "✅ " if check_version(current, str(r.specifier), name=r.name, hard=True) else "❌ "
763
+ except metadata.PackageNotFoundError:
764
+ current = "(not installed)"
765
+ is_met = "❌ "
766
+ package_info[r.name] = f"{is_met}{current}{r.specifier}"
767
+ LOGGER.info(f"{r.name:<23}{package_info[r.name]}")
768
+
769
+ info_dict["Package Info"] = package_info
770
+
771
+ if is_github_action_running():
772
+ github_info = {
773
+ "RUNNER_OS": os.getenv("RUNNER_OS"),
774
+ "GITHUB_EVENT_NAME": os.getenv("GITHUB_EVENT_NAME"),
775
+ "GITHUB_WORKFLOW": os.getenv("GITHUB_WORKFLOW"),
776
+ "GITHUB_ACTOR": os.getenv("GITHUB_ACTOR"),
777
+ "GITHUB_REPOSITORY": os.getenv("GITHUB_REPOSITORY"),
778
+ "GITHUB_REPOSITORY_OWNER": os.getenv("GITHUB_REPOSITORY_OWNER"),
779
+ }
780
+ LOGGER.info("\n" + "\n".join(f"{k}: {v}" for k, v in github_info.items()))
781
+ info_dict["GitHub Info"] = github_info
782
+
783
+ return info_dict
784
+
785
+
786
+ def check_amp(model):
787
+ """Check the PyTorch Automatic Mixed Precision (AMP) functionality of a YOLO model.
788
+
789
+ If the checks fail, it means there are anomalies with AMP on the system that may cause NaN losses or zero-mAP
790
+ results, so AMP will be disabled during training.
791
+
792
+ Args:
793
+ model (torch.nn.Module): A YOLO model instance.
794
+
795
+ Returns:
796
+ (bool): Returns True if the AMP functionality works correctly with YOLO11 model, else False.
797
+
798
+ Examples:
799
+ >>> from ultralytics import YOLO
800
+ >>> from ultralytics.utils.checks import check_amp
801
+ >>> model = YOLO("yolo11n.pt").model.cuda()
802
+ >>> check_amp(model)
803
+ """
804
+ from ultralytics.utils.torch_utils import autocast
805
+
806
+ device = next(model.parameters()).device # get model device
807
+ prefix = colorstr("AMP: ")
808
+ if device.type in {"cpu", "mps"}:
809
+ return False # AMP only used on CUDA devices
810
+ else:
811
+ # GPUs that have issues with AMP
812
+ pattern = re.compile(
813
+ r"(nvidia|geforce|quadro|tesla).*?(1660|1650|1630|t400|t550|t600|t1000|t1200|t2000|k40m)", re.IGNORECASE
814
+ )
815
+
816
+ gpu = torch.cuda.get_device_name(device)
817
+ if bool(pattern.search(gpu)):
818
+ LOGGER.warning(
819
+ f"{prefix}checks failed ❌. AMP training on {gpu} GPU may cause "
820
+ f"NaN losses or zero-mAP results, so AMP will be disabled during training."
821
+ )
822
+ return False
823
+
824
+ def amp_allclose(m, im):
825
+ """All close FP32 vs AMP results."""
826
+ batch = [im] * 8
827
+ imgsz = max(256, int(model.stride.max() * 4)) # max stride P5-32 and P6-64
828
+ a = m(batch, imgsz=imgsz, device=device, verbose=False)[0].boxes.data # FP32 inference
829
+ with autocast(enabled=True):
830
+ b = m(batch, imgsz=imgsz, device=device, verbose=False)[0].boxes.data # AMP inference
831
+ del m
832
+ return a.shape == b.shape and torch.allclose(a, b.float(), atol=0.5) # close to 0.5 absolute tolerance
833
+
834
+ im = ASSETS / "bus.jpg" # image to check
835
+ LOGGER.info(f"{prefix}running Automatic Mixed Precision (AMP) checks...")
836
+ warning_msg = "Setting 'amp=True'. If you experience zero-mAP or NaN losses you can disable AMP with amp=False."
837
+ try:
838
+ from ultralytics import YOLO
839
+
840
+ assert amp_allclose(YOLO("yolo11n.pt"), im)
841
+ LOGGER.info(f"{prefix}checks passed ✅")
842
+ except ConnectionError:
843
+ LOGGER.warning(f"{prefix}checks skipped. Offline and unable to download YOLO11n for AMP checks. {warning_msg}")
844
+ except (AttributeError, ModuleNotFoundError):
845
+ LOGGER.warning(
846
+ f"{prefix}checks skipped. "
847
+ f"Unable to load YOLO11n for AMP checks due to possible Ultralytics package modifications. {warning_msg}"
848
+ )
849
+ except AssertionError:
850
+ LOGGER.error(
851
+ f"{prefix}checks failed. Anomalies were detected with AMP on your system that may lead to "
852
+ f"NaN losses or zero-mAP results, so AMP will be disabled during training."
853
+ )
854
+ return False
855
+ return True
856
+
857
+
858
+ def check_multiple_install():
859
+ """Check if there are multiple Ultralytics installations."""
860
+ import sys
861
+
862
+ try:
863
+ result = subprocess.run([sys.executable, "-m", "pip", "show", "ultralytics"], capture_output=True, text=True)
864
+ install_msg = (
865
+ f"Install your local copy in editable mode with 'pip install -e {ROOT.parent}' to avoid "
866
+ "issues. See https://docs.ultralytics.com/quickstart/"
867
+ )
868
+ if result.returncode != 0:
869
+ if "not found" in result.stderr.lower(): # Package not pip-installed but locally imported
870
+ LOGGER.warning(f"Ultralytics not found via pip but importing from: {ROOT}. {install_msg}")
871
+ return
872
+ yolo_path = (Path(re.findall(r"location:\s+(.+)", result.stdout, flags=re.I)[-1]) / "ultralytics").resolve()
873
+ if not yolo_path.samefile(ROOT.resolve()):
874
+ LOGGER.warning(
875
+ f"Multiple Ultralytics installations detected. The `yolo` command uses: {yolo_path}, "
876
+ f"but current session imports from: {ROOT}. This may cause version conflicts. {install_msg}"
877
+ )
878
+ except Exception:
879
+ return
880
+
881
+
882
+ def print_args(args: dict | None = None, show_file=True, show_func=False):
883
+ """Print function arguments (optional args dict).
884
+
885
+ Args:
886
+ args (dict, optional): Arguments to print.
887
+ show_file (bool): Whether to show the file name.
888
+ show_func (bool): Whether to show the function name.
889
+ """
890
+
891
+ def strip_auth(v):
892
+ """Clean longer Ultralytics HUB URLs by stripping potential authentication information."""
893
+ return clean_url(v) if (isinstance(v, str) and v.startswith("http") and len(v) > 100) else v
894
+
895
+ x = inspect.currentframe().f_back # previous frame
896
+ file, _, func, _, _ = inspect.getframeinfo(x)
897
+ if args is None: # get args automatically
898
+ args, _, _, frm = inspect.getargvalues(x)
899
+ args = {k: v for k, v in frm.items() if k in args}
900
+ try:
901
+ file = Path(file).resolve().relative_to(ROOT).with_suffix("")
902
+ except ValueError:
903
+ file = Path(file).stem
904
+ s = (f"{file}: " if show_file else "") + (f"{func}: " if show_func else "")
905
+ LOGGER.info(colorstr(s) + ", ".join(f"{k}={strip_auth(v)}" for k, v in sorted(args.items())))
906
+
907
+
908
+ def cuda_device_count() -> int:
909
+ """Get the number of NVIDIA GPUs available in the environment.
910
+
911
+ Returns:
912
+ (int): The number of NVIDIA GPUs available.
913
+ """
914
+ if IS_JETSON:
915
+ # NVIDIA Jetson does not fully support nvidia-smi and therefore use PyTorch instead
916
+ return torch.cuda.device_count()
917
+ else:
918
+ try:
919
+ # Run the nvidia-smi command and capture its output
920
+ output = subprocess.check_output(
921
+ ["nvidia-smi", "--query-gpu=count", "--format=csv,noheader,nounits"], encoding="utf-8"
922
+ )
923
+
924
+ # Take the first line and strip any leading/trailing white space
925
+ first_line = output.strip().split("\n", 1)[0]
926
+
927
+ return int(first_line)
928
+ except (subprocess.CalledProcessError, FileNotFoundError, ValueError):
929
+ # If the command fails, nvidia-smi is not found, or output is not an integer, assume no GPUs are available
930
+ return 0
931
+
932
+
933
+ def cuda_is_available() -> bool:
934
+ """Check if CUDA is available in the environment.
935
+
936
+ Returns:
937
+ (bool): True if one or more NVIDIA GPUs are available, False otherwise.
938
+ """
939
+ return cuda_device_count() > 0
940
+
941
+
942
+ def is_rockchip():
943
+ """Check if the current environment is running on a Rockchip SoC.
944
+
945
+ Returns:
946
+ (bool): True if running on a Rockchip SoC, False otherwise.
947
+ """
948
+ if LINUX and ARM64:
949
+ try:
950
+ with open("/proc/device-tree/compatible") as f:
951
+ dev_str = f.read()
952
+ *_, soc = dev_str.split(",")
953
+ if soc.replace("\x00", "") in RKNN_CHIPS:
954
+ return True
955
+ except OSError:
956
+ return False
957
+ else:
958
+ return False
959
+
960
+
961
+ def is_intel():
962
+ """Check if the system has Intel hardware (CPU or GPU).
963
+
964
+ Returns:
965
+ (bool): True if Intel hardware is detected, False otherwise.
966
+ """
967
+ from ultralytics.utils.torch_utils import get_cpu_info
968
+
969
+ # Check CPU
970
+ if "intel" in get_cpu_info().lower():
971
+ return True
972
+
973
+ # Check GPU via xpu-smi
974
+ try:
975
+ result = subprocess.run(["xpu-smi", "discovery"], capture_output=True, text=True, timeout=5)
976
+ return "intel" in result.stdout.lower()
977
+ except Exception: # broad clause to capture all Intel GPU exception types
978
+ return False
979
+
980
+
981
+ def is_sudo_available() -> bool:
982
+ """Check if the sudo command is available in the environment.
983
+
984
+ Returns:
985
+ (bool): True if the sudo command is available, False otherwise.
986
+ """
987
+ if WINDOWS:
988
+ return False
989
+ cmd = "sudo --version"
990
+ return subprocess.run(cmd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
991
+
992
+
993
+ # Run checks and define constants
994
+ check_python("3.8", hard=False, verbose=True) # check python version
995
+ check_torchvision() # check torch-torchvision compatibility
996
+
997
+ # Define constants
998
+ IS_PYTHON_3_8 = PYTHON_VERSION.startswith("3.8")
999
+ IS_PYTHON_3_9 = PYTHON_VERSION.startswith("3.9")
1000
+ IS_PYTHON_3_10 = PYTHON_VERSION.startswith("3.10")
1001
+ IS_PYTHON_3_12 = PYTHON_VERSION.startswith("3.12")
1002
+ IS_PYTHON_3_13 = PYTHON_VERSION.startswith("3.13")
1003
+
1004
+ IS_PYTHON_MINIMUM_3_9 = check_python("3.9", hard=False)
1005
+ IS_PYTHON_MINIMUM_3_10 = check_python("3.10", hard=False)
1006
+ IS_PYTHON_MINIMUM_3_12 = check_python("3.12", hard=False)