ultralytics-opencv-headless 8.3.242__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 +1574 -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 +73 -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 +998 -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 +444 -0
  282. ultralytics/utils/loss.py +849 -0
  283. ultralytics/utils/metrics.py +1560 -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.242.dist-info/METADATA +374 -0
  294. ultralytics_opencv_headless-8.3.242.dist-info/RECORD +298 -0
  295. ultralytics_opencv_headless-8.3.242.dist-info/WHEEL +5 -0
  296. ultralytics_opencv_headless-8.3.242.dist-info/entry_points.txt +3 -0
  297. ultralytics_opencv_headless-8.3.242.dist-info/licenses/LICENSE +661 -0
  298. ultralytics_opencv_headless-8.3.242.dist-info/top_level.txt +1 -0
@@ -0,0 +1,484 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import abc
6
+ from itertools import repeat
7
+ from numbers import Number
8
+
9
+ import numpy as np
10
+
11
+ from .ops import ltwh2xywh, ltwh2xyxy, resample_segments, xywh2ltwh, xywh2xyxy, xyxy2ltwh, xyxy2xywh
12
+
13
+
14
+ def _ntuple(n):
15
+ """Create a function that converts input to n-tuple by repeating singleton values."""
16
+
17
+ def parse(x):
18
+ """Parse input to return n-tuple by repeating singleton values n times."""
19
+ return x if isinstance(x, abc.Iterable) else tuple(repeat(x, n))
20
+
21
+ return parse
22
+
23
+
24
+ to_2tuple = _ntuple(2)
25
+ to_4tuple = _ntuple(4)
26
+
27
+ # `xyxy` means left top and right bottom
28
+ # `xywh` means center x, center y and width, height(YOLO format)
29
+ # `ltwh` means left top and width, height(COCO format)
30
+ _formats = ["xyxy", "xywh", "ltwh"]
31
+
32
+ __all__ = ("Bboxes", "Instances") # tuple or list
33
+
34
+
35
+ class Bboxes:
36
+ """A class for handling bounding boxes in multiple formats.
37
+
38
+ The class supports various bounding box formats like 'xyxy', 'xywh', and 'ltwh' and provides methods for format
39
+ conversion, scaling, and area calculation. Bounding box data should be provided as numpy arrays.
40
+
41
+ Attributes:
42
+ bboxes (np.ndarray): The bounding boxes stored in a 2D numpy array with shape (N, 4).
43
+ format (str): The format of the bounding boxes ('xyxy', 'xywh', or 'ltwh').
44
+
45
+ Methods:
46
+ convert: Convert bounding box format from one type to another.
47
+ areas: Calculate the area of bounding boxes.
48
+ mul: Multiply bounding box coordinates by scale factor(s).
49
+ add: Add offset to bounding box coordinates.
50
+ concatenate: Concatenate multiple Bboxes objects.
51
+
52
+ Examples:
53
+ Create bounding boxes in YOLO format
54
+ >>> bboxes = Bboxes(np.array([[100, 50, 150, 100]]), format="xywh")
55
+ >>> bboxes.convert("xyxy")
56
+ >>> print(bboxes.areas())
57
+
58
+ Notes:
59
+ This class does not handle normalization or denormalization of bounding boxes.
60
+ """
61
+
62
+ def __init__(self, bboxes: np.ndarray, format: str = "xyxy") -> None:
63
+ """Initialize the Bboxes class with bounding box data in a specified format.
64
+
65
+ Args:
66
+ bboxes (np.ndarray): Array of bounding boxes with shape (N, 4) or (4,).
67
+ format (str): Format of the bounding boxes, one of 'xyxy', 'xywh', or 'ltwh'.
68
+ """
69
+ assert format in _formats, f"Invalid bounding box format: {format}, format must be one of {_formats}"
70
+ bboxes = bboxes[None, :] if bboxes.ndim == 1 else bboxes
71
+ assert bboxes.ndim == 2
72
+ assert bboxes.shape[1] == 4
73
+ self.bboxes = bboxes
74
+ self.format = format
75
+
76
+ def convert(self, format: str) -> None:
77
+ """Convert bounding box format from one type to another.
78
+
79
+ Args:
80
+ format (str): Target format for conversion, one of 'xyxy', 'xywh', or 'ltwh'.
81
+ """
82
+ assert format in _formats, f"Invalid bounding box format: {format}, format must be one of {_formats}"
83
+ if self.format == format:
84
+ return
85
+ elif self.format == "xyxy":
86
+ func = xyxy2xywh if format == "xywh" else xyxy2ltwh
87
+ elif self.format == "xywh":
88
+ func = xywh2xyxy if format == "xyxy" else xywh2ltwh
89
+ else:
90
+ func = ltwh2xyxy if format == "xyxy" else ltwh2xywh
91
+ self.bboxes = func(self.bboxes)
92
+ self.format = format
93
+
94
+ def areas(self) -> np.ndarray:
95
+ """Calculate the area of bounding boxes."""
96
+ return (
97
+ (self.bboxes[:, 2] - self.bboxes[:, 0]) * (self.bboxes[:, 3] - self.bboxes[:, 1]) # format xyxy
98
+ if self.format == "xyxy"
99
+ else self.bboxes[:, 3] * self.bboxes[:, 2] # format xywh or ltwh
100
+ )
101
+
102
+ def mul(self, scale: int | tuple | list) -> None:
103
+ """Multiply bounding box coordinates by scale factor(s).
104
+
105
+ Args:
106
+ scale (int | tuple | list): Scale factor(s) for four coordinates. If int, the same scale is applied to all
107
+ coordinates.
108
+ """
109
+ if isinstance(scale, Number):
110
+ scale = to_4tuple(scale)
111
+ assert isinstance(scale, (tuple, list))
112
+ assert len(scale) == 4
113
+ self.bboxes[:, 0] *= scale[0]
114
+ self.bboxes[:, 1] *= scale[1]
115
+ self.bboxes[:, 2] *= scale[2]
116
+ self.bboxes[:, 3] *= scale[3]
117
+
118
+ def add(self, offset: int | tuple | list) -> None:
119
+ """Add offset to bounding box coordinates.
120
+
121
+ Args:
122
+ offset (int | tuple | list): Offset(s) for four coordinates. If int, the same offset is applied to all
123
+ coordinates.
124
+ """
125
+ if isinstance(offset, Number):
126
+ offset = to_4tuple(offset)
127
+ assert isinstance(offset, (tuple, list))
128
+ assert len(offset) == 4
129
+ self.bboxes[:, 0] += offset[0]
130
+ self.bboxes[:, 1] += offset[1]
131
+ self.bboxes[:, 2] += offset[2]
132
+ self.bboxes[:, 3] += offset[3]
133
+
134
+ def __len__(self) -> int:
135
+ """Return the number of bounding boxes."""
136
+ return len(self.bboxes)
137
+
138
+ @classmethod
139
+ def concatenate(cls, boxes_list: list[Bboxes], axis: int = 0) -> Bboxes:
140
+ """Concatenate a list of Bboxes objects into a single Bboxes object.
141
+
142
+ Args:
143
+ boxes_list (list[Bboxes]): A list of Bboxes objects to concatenate.
144
+ axis (int, optional): The axis along which to concatenate the bounding boxes.
145
+
146
+ Returns:
147
+ (Bboxes): A new Bboxes object containing the concatenated bounding boxes.
148
+
149
+ Notes:
150
+ The input should be a list or tuple of Bboxes objects.
151
+ """
152
+ assert isinstance(boxes_list, (list, tuple))
153
+ if not boxes_list:
154
+ return cls(np.empty(0))
155
+ assert all(isinstance(box, Bboxes) for box in boxes_list)
156
+
157
+ if len(boxes_list) == 1:
158
+ return boxes_list[0]
159
+ return cls(np.concatenate([b.bboxes for b in boxes_list], axis=axis))
160
+
161
+ def __getitem__(self, index: int | np.ndarray | slice) -> Bboxes:
162
+ """Retrieve a specific bounding box or a set of bounding boxes using indexing.
163
+
164
+ Args:
165
+ index (int | slice | np.ndarray): The index, slice, or boolean array to select the desired bounding boxes.
166
+
167
+ Returns:
168
+ (Bboxes): A new Bboxes object containing the selected bounding boxes.
169
+
170
+ Notes:
171
+ When using boolean indexing, make sure to provide a boolean array with the same length as the number of
172
+ bounding boxes.
173
+ """
174
+ if isinstance(index, int):
175
+ return Bboxes(self.bboxes[index].reshape(1, -1))
176
+ b = self.bboxes[index]
177
+ assert b.ndim == 2, f"Indexing on Bboxes with {index} failed to return a matrix!"
178
+ return Bboxes(b)
179
+
180
+
181
+ class Instances:
182
+ """Container for bounding boxes, segments, and keypoints of detected objects in an image.
183
+
184
+ This class provides a unified interface for handling different types of object annotations including bounding boxes,
185
+ segmentation masks, and keypoints. It supports various operations like scaling, normalization, clipping, and format
186
+ conversion.
187
+
188
+ Attributes:
189
+ _bboxes (Bboxes): Internal object for handling bounding box operations.
190
+ keypoints (np.ndarray): Keypoints with shape (N, 17, 3) in format (x, y, visible).
191
+ normalized (bool): Flag indicating whether the bounding box coordinates are normalized.
192
+ segments (np.ndarray): Segments array with shape (N, M, 2) after resampling.
193
+
194
+ Methods:
195
+ convert_bbox: Convert bounding box format.
196
+ scale: Scale coordinates by given factors.
197
+ denormalize: Convert normalized coordinates to absolute coordinates.
198
+ normalize: Convert absolute coordinates to normalized coordinates.
199
+ add_padding: Add padding to coordinates.
200
+ flipud: Flip coordinates vertically.
201
+ fliplr: Flip coordinates horizontally.
202
+ clip: Clip coordinates to stay within image boundaries.
203
+ remove_zero_area_boxes: Remove boxes with zero area.
204
+ update: Update instance variables.
205
+ concatenate: Concatenate multiple Instances objects.
206
+
207
+ Examples:
208
+ Create instances with bounding boxes and segments
209
+ >>> instances = Instances(
210
+ ... bboxes=np.array([[10, 10, 30, 30], [20, 20, 40, 40]]),
211
+ ... segments=[np.array([[5, 5], [10, 10]]), np.array([[15, 15], [20, 20]])],
212
+ ... keypoints=np.array([[[5, 5, 1], [10, 10, 1]], [[15, 15, 1], [20, 20, 1]]]),
213
+ ... )
214
+ """
215
+
216
+ def __init__(
217
+ self,
218
+ bboxes: np.ndarray,
219
+ segments: np.ndarray = None,
220
+ keypoints: np.ndarray = None,
221
+ bbox_format: str = "xywh",
222
+ normalized: bool = True,
223
+ ) -> None:
224
+ """Initialize the Instances object with bounding boxes, segments, and keypoints.
225
+
226
+ Args:
227
+ bboxes (np.ndarray): Bounding boxes with shape (N, 4).
228
+ segments (np.ndarray, optional): Segmentation masks.
229
+ keypoints (np.ndarray, optional): Keypoints with shape (N, 17, 3) in format (x, y, visible).
230
+ bbox_format (str): Format of bboxes.
231
+ normalized (bool): Whether the coordinates are normalized.
232
+ """
233
+ self._bboxes = Bboxes(bboxes=bboxes, format=bbox_format)
234
+ self.keypoints = keypoints
235
+ self.normalized = normalized
236
+ self.segments = segments
237
+
238
+ def convert_bbox(self, format: str) -> None:
239
+ """Convert bounding box format.
240
+
241
+ Args:
242
+ format (str): Target format for conversion, one of 'xyxy', 'xywh', or 'ltwh'.
243
+ """
244
+ self._bboxes.convert(format=format)
245
+
246
+ @property
247
+ def bbox_areas(self) -> np.ndarray:
248
+ """Calculate the area of bounding boxes."""
249
+ return self._bboxes.areas()
250
+
251
+ def scale(self, scale_w: float, scale_h: float, bbox_only: bool = False):
252
+ """Scale coordinates by given factors.
253
+
254
+ Args:
255
+ scale_w (float): Scale factor for width.
256
+ scale_h (float): Scale factor for height.
257
+ bbox_only (bool, optional): Whether to scale only bounding boxes.
258
+ """
259
+ self._bboxes.mul(scale=(scale_w, scale_h, scale_w, scale_h))
260
+ if bbox_only:
261
+ return
262
+ self.segments[..., 0] *= scale_w
263
+ self.segments[..., 1] *= scale_h
264
+ if self.keypoints is not None:
265
+ self.keypoints[..., 0] *= scale_w
266
+ self.keypoints[..., 1] *= scale_h
267
+
268
+ def denormalize(self, w: int, h: int) -> None:
269
+ """Convert normalized coordinates to absolute coordinates.
270
+
271
+ Args:
272
+ w (int): Image width.
273
+ h (int): Image height.
274
+ """
275
+ if not self.normalized:
276
+ return
277
+ self._bboxes.mul(scale=(w, h, w, h))
278
+ self.segments[..., 0] *= w
279
+ self.segments[..., 1] *= h
280
+ if self.keypoints is not None:
281
+ self.keypoints[..., 0] *= w
282
+ self.keypoints[..., 1] *= h
283
+ self.normalized = False
284
+
285
+ def normalize(self, w: int, h: int) -> None:
286
+ """Convert absolute coordinates to normalized coordinates.
287
+
288
+ Args:
289
+ w (int): Image width.
290
+ h (int): Image height.
291
+ """
292
+ if self.normalized:
293
+ return
294
+ self._bboxes.mul(scale=(1 / w, 1 / h, 1 / w, 1 / h))
295
+ self.segments[..., 0] /= w
296
+ self.segments[..., 1] /= h
297
+ if self.keypoints is not None:
298
+ self.keypoints[..., 0] /= w
299
+ self.keypoints[..., 1] /= h
300
+ self.normalized = True
301
+
302
+ def add_padding(self, padw: int, padh: int) -> None:
303
+ """Add padding to coordinates.
304
+
305
+ Args:
306
+ padw (int): Padding width.
307
+ padh (int): Padding height.
308
+ """
309
+ assert not self.normalized, "you should add padding with absolute coordinates."
310
+ self._bboxes.add(offset=(padw, padh, padw, padh))
311
+ self.segments[..., 0] += padw
312
+ self.segments[..., 1] += padh
313
+ if self.keypoints is not None:
314
+ self.keypoints[..., 0] += padw
315
+ self.keypoints[..., 1] += padh
316
+
317
+ def __getitem__(self, index: int | np.ndarray | slice) -> Instances:
318
+ """Retrieve a specific instance or a set of instances using indexing.
319
+
320
+ Args:
321
+ index (int | slice | np.ndarray): The index, slice, or boolean array to select the desired instances.
322
+
323
+ Returns:
324
+ (Instances): A new Instances object containing the selected boxes, segments, and keypoints if present.
325
+
326
+ Notes:
327
+ When using boolean indexing, make sure to provide a boolean array with the same length as the number of
328
+ instances.
329
+ """
330
+ segments = self.segments[index] if len(self.segments) else self.segments
331
+ keypoints = self.keypoints[index] if self.keypoints is not None else None
332
+ bboxes = self.bboxes[index]
333
+ bbox_format = self._bboxes.format
334
+ return Instances(
335
+ bboxes=bboxes,
336
+ segments=segments,
337
+ keypoints=keypoints,
338
+ bbox_format=bbox_format,
339
+ normalized=self.normalized,
340
+ )
341
+
342
+ def flipud(self, h: int) -> None:
343
+ """Flip coordinates vertically.
344
+
345
+ Args:
346
+ h (int): Image height.
347
+ """
348
+ if self._bboxes.format == "xyxy":
349
+ y1 = self.bboxes[:, 1].copy()
350
+ y2 = self.bboxes[:, 3].copy()
351
+ self.bboxes[:, 1] = h - y2
352
+ self.bboxes[:, 3] = h - y1
353
+ else:
354
+ self.bboxes[:, 1] = h - self.bboxes[:, 1]
355
+ self.segments[..., 1] = h - self.segments[..., 1]
356
+ if self.keypoints is not None:
357
+ self.keypoints[..., 1] = h - self.keypoints[..., 1]
358
+
359
+ def fliplr(self, w: int) -> None:
360
+ """Flip coordinates horizontally.
361
+
362
+ Args:
363
+ w (int): Image width.
364
+ """
365
+ if self._bboxes.format == "xyxy":
366
+ x1 = self.bboxes[:, 0].copy()
367
+ x2 = self.bboxes[:, 2].copy()
368
+ self.bboxes[:, 0] = w - x2
369
+ self.bboxes[:, 2] = w - x1
370
+ else:
371
+ self.bboxes[:, 0] = w - self.bboxes[:, 0]
372
+ self.segments[..., 0] = w - self.segments[..., 0]
373
+ if self.keypoints is not None:
374
+ self.keypoints[..., 0] = w - self.keypoints[..., 0]
375
+
376
+ def clip(self, w: int, h: int) -> None:
377
+ """Clip coordinates to stay within image boundaries.
378
+
379
+ Args:
380
+ w (int): Image width.
381
+ h (int): Image height.
382
+ """
383
+ ori_format = self._bboxes.format
384
+ self.convert_bbox(format="xyxy")
385
+ self.bboxes[:, [0, 2]] = self.bboxes[:, [0, 2]].clip(0, w)
386
+ self.bboxes[:, [1, 3]] = self.bboxes[:, [1, 3]].clip(0, h)
387
+ if ori_format != "xyxy":
388
+ self.convert_bbox(format=ori_format)
389
+ self.segments[..., 0] = self.segments[..., 0].clip(0, w)
390
+ self.segments[..., 1] = self.segments[..., 1].clip(0, h)
391
+ if self.keypoints is not None:
392
+ # Set out of bounds visibility to zero
393
+ self.keypoints[..., 2][
394
+ (self.keypoints[..., 0] < 0)
395
+ | (self.keypoints[..., 0] > w)
396
+ | (self.keypoints[..., 1] < 0)
397
+ | (self.keypoints[..., 1] > h)
398
+ ] = 0.0
399
+ self.keypoints[..., 0] = self.keypoints[..., 0].clip(0, w)
400
+ self.keypoints[..., 1] = self.keypoints[..., 1].clip(0, h)
401
+
402
+ def remove_zero_area_boxes(self) -> np.ndarray:
403
+ """Remove zero-area boxes, i.e. after clipping some boxes may have zero width or height.
404
+
405
+ Returns:
406
+ (np.ndarray): Boolean array indicating which boxes were kept.
407
+ """
408
+ good = self.bbox_areas > 0
409
+ if not all(good):
410
+ self._bboxes = self._bboxes[good]
411
+ if len(self.segments):
412
+ self.segments = self.segments[good]
413
+ if self.keypoints is not None:
414
+ self.keypoints = self.keypoints[good]
415
+ return good
416
+
417
+ def update(self, bboxes: np.ndarray, segments: np.ndarray = None, keypoints: np.ndarray = None):
418
+ """Update instance variables.
419
+
420
+ Args:
421
+ bboxes (np.ndarray): New bounding boxes.
422
+ segments (np.ndarray, optional): New segments.
423
+ keypoints (np.ndarray, optional): New keypoints.
424
+ """
425
+ self._bboxes = Bboxes(bboxes, format=self._bboxes.format)
426
+ if segments is not None:
427
+ self.segments = segments
428
+ if keypoints is not None:
429
+ self.keypoints = keypoints
430
+
431
+ def __len__(self) -> int:
432
+ """Return the number of instances."""
433
+ return len(self.bboxes)
434
+
435
+ @classmethod
436
+ def concatenate(cls, instances_list: list[Instances], axis=0) -> Instances:
437
+ """Concatenate a list of Instances objects into a single Instances object.
438
+
439
+ Args:
440
+ instances_list (list[Instances]): A list of Instances objects to concatenate.
441
+ axis (int, optional): The axis along which the arrays will be concatenated.
442
+
443
+ Returns:
444
+ (Instances): A new Instances object containing the concatenated bounding boxes, segments, and keypoints if
445
+ present.
446
+
447
+ Notes:
448
+ The `Instances` objects in the list should have the same properties, such as the format of the bounding
449
+ boxes, whether keypoints are present, and if the coordinates are normalized.
450
+ """
451
+ assert isinstance(instances_list, (list, tuple))
452
+ if not instances_list:
453
+ return cls(np.empty(0))
454
+ assert all(isinstance(instance, Instances) for instance in instances_list)
455
+
456
+ if len(instances_list) == 1:
457
+ return instances_list[0]
458
+
459
+ use_keypoint = instances_list[0].keypoints is not None
460
+ bbox_format = instances_list[0]._bboxes.format
461
+ normalized = instances_list[0].normalized
462
+
463
+ cat_boxes = np.concatenate([ins.bboxes for ins in instances_list], axis=axis)
464
+ seg_len = [b.segments.shape[1] for b in instances_list]
465
+ if len(frozenset(seg_len)) > 1: # resample segments if there's different length
466
+ max_len = max(seg_len)
467
+ cat_segments = np.concatenate(
468
+ [
469
+ resample_segments(list(b.segments), max_len)
470
+ if len(b.segments)
471
+ else np.zeros((0, max_len, 2), dtype=np.float32) # re-generating empty segments
472
+ for b in instances_list
473
+ ],
474
+ axis=axis,
475
+ )
476
+ else:
477
+ cat_segments = np.concatenate([b.segments for b in instances_list], axis=axis)
478
+ cat_keypoints = np.concatenate([b.keypoints for b in instances_list], axis=axis) if use_keypoint else None
479
+ return cls(cat_boxes, cat_segments, cat_keypoints, bbox_format, normalized)
480
+
481
+ @property
482
+ def bboxes(self) -> np.ndarray:
483
+ """Return bounding boxes."""
484
+ return self._bboxes.bboxes