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,1560 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+ """Model validation metrics."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import math
7
+ import warnings
8
+ from collections import defaultdict
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import numpy as np
13
+ import torch
14
+
15
+ from ultralytics.utils import LOGGER, DataExportMixin, SimpleClass, TryExcept, checks, plt_settings
16
+
17
+ OKS_SIGMA = (
18
+ np.array(
19
+ [0.26, 0.25, 0.25, 0.35, 0.35, 0.79, 0.79, 0.72, 0.72, 0.62, 0.62, 1.07, 1.07, 0.87, 0.87, 0.89, 0.89],
20
+ dtype=np.float32,
21
+ )
22
+ / 10.0
23
+ )
24
+
25
+
26
+ def bbox_ioa(box1: np.ndarray, box2: np.ndarray, iou: bool = False, eps: float = 1e-7) -> np.ndarray:
27
+ """Calculate the intersection over box2 area given box1 and box2.
28
+
29
+ Args:
30
+ box1 (np.ndarray): A numpy array of shape (N, 4) representing N bounding boxes in x1y1x2y2 format.
31
+ box2 (np.ndarray): A numpy array of shape (M, 4) representing M bounding boxes in x1y1x2y2 format.
32
+ iou (bool, optional): Calculate the standard IoU if True else return inter_area/box2_area.
33
+ eps (float, optional): A small value to avoid division by zero.
34
+
35
+ Returns:
36
+ (np.ndarray): A numpy array of shape (N, M) representing the intersection over box2 area.
37
+ """
38
+ # Get the coordinates of bounding boxes
39
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1.T
40
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2.T
41
+
42
+ # Intersection area
43
+ inter_area = (np.minimum(b1_x2[:, None], b2_x2) - np.maximum(b1_x1[:, None], b2_x1)).clip(0) * (
44
+ np.minimum(b1_y2[:, None], b2_y2) - np.maximum(b1_y1[:, None], b2_y1)
45
+ ).clip(0)
46
+
47
+ # Box2 area
48
+ area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1)
49
+ if iou:
50
+ box1_area = (b1_x2 - b1_x1) * (b1_y2 - b1_y1)
51
+ area = area + box1_area[:, None] - inter_area
52
+
53
+ # Intersection over box2 area
54
+ return inter_area / (area + eps)
55
+
56
+
57
+ def box_iou(box1: torch.Tensor, box2: torch.Tensor, eps: float = 1e-7) -> torch.Tensor:
58
+ """Calculate intersection-over-union (IoU) of boxes.
59
+
60
+ Args:
61
+ box1 (torch.Tensor): A tensor of shape (N, 4) representing N bounding boxes in (x1, y1, x2, y2) format.
62
+ box2 (torch.Tensor): A tensor of shape (M, 4) representing M bounding boxes in (x1, y1, x2, y2) format.
63
+ eps (float, optional): A small value to avoid division by zero.
64
+
65
+ Returns:
66
+ (torch.Tensor): An NxM tensor containing the pairwise IoU values for every element in box1 and box2.
67
+
68
+ References:
69
+ https://github.com/pytorch/vision/blob/main/torchvision/ops/boxes.py
70
+ """
71
+ # NOTE: Need .float() to get accurate iou values
72
+ # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
73
+ (a1, a2), (b1, b2) = box1.float().unsqueeze(1).chunk(2, 2), box2.float().unsqueeze(0).chunk(2, 2)
74
+ inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp_(0).prod(2)
75
+
76
+ # IoU = inter / (area1 + area2 - inter)
77
+ return inter / ((a2 - a1).prod(2) + (b2 - b1).prod(2) - inter + eps)
78
+
79
+
80
+ def bbox_iou(
81
+ box1: torch.Tensor,
82
+ box2: torch.Tensor,
83
+ xywh: bool = True,
84
+ GIoU: bool = False,
85
+ DIoU: bool = False,
86
+ CIoU: bool = False,
87
+ eps: float = 1e-7,
88
+ ) -> torch.Tensor:
89
+ """Calculate the Intersection over Union (IoU) between bounding boxes.
90
+
91
+ This function supports various shapes for `box1` and `box2` as long as the last dimension is 4. For instance, you
92
+ may pass tensors shaped like (4,), (N, 4), (B, N, 4), or (B, N, 1, 4). Internally, the code will split the last
93
+ dimension into (x, y, w, h) if `xywh=True`, or (x1, y1, x2, y2) if `xywh=False`.
94
+
95
+ Args:
96
+ box1 (torch.Tensor): A tensor representing one or more bounding boxes, with the last dimension being 4.
97
+ box2 (torch.Tensor): A tensor representing one or more bounding boxes, with the last dimension being 4.
98
+ xywh (bool, optional): If True, input boxes are in (x, y, w, h) format. If False, input boxes are in (x1, y1,
99
+ x2, y2) format.
100
+ GIoU (bool, optional): If True, calculate Generalized IoU.
101
+ DIoU (bool, optional): If True, calculate Distance IoU.
102
+ CIoU (bool, optional): If True, calculate Complete IoU.
103
+ eps (float, optional): A small value to avoid division by zero.
104
+
105
+ Returns:
106
+ (torch.Tensor): IoU, GIoU, DIoU, or CIoU values depending on the specified flags.
107
+ """
108
+ # Get the coordinates of bounding boxes
109
+ if xywh: # transform from xywh to xyxy
110
+ (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
111
+ w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
112
+ b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
113
+ b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
114
+ else: # x1, y1, x2, y2 = box1
115
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
116
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
117
+ w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
118
+ w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
119
+
120
+ # Intersection area
121
+ inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp_(0) * (
122
+ b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)
123
+ ).clamp_(0)
124
+
125
+ # Union Area
126
+ union = w1 * h1 + w2 * h2 - inter + eps
127
+
128
+ # IoU
129
+ iou = inter / union
130
+ if CIoU or DIoU or GIoU:
131
+ cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1) # convex (smallest enclosing box) width
132
+ ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1) # convex height
133
+ if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
134
+ c2 = cw.pow(2) + ch.pow(2) + eps # convex diagonal squared
135
+ rho2 = (
136
+ (b2_x1 + b2_x2 - b1_x1 - b1_x2).pow(2) + (b2_y1 + b2_y2 - b1_y1 - b1_y2).pow(2)
137
+ ) / 4 # center dist**2
138
+ if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
139
+ v = (4 / math.pi**2) * ((w2 / h2).atan() - (w1 / h1).atan()).pow(2)
140
+ with torch.no_grad():
141
+ alpha = v / (v - iou + (1 + eps))
142
+ return iou - (rho2 / c2 + v * alpha) # CIoU
143
+ return iou - rho2 / c2 # DIoU
144
+ c_area = cw * ch + eps # convex area
145
+ return iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf
146
+ return iou # IoU
147
+
148
+
149
+ def mask_iou(mask1: torch.Tensor, mask2: torch.Tensor, eps: float = 1e-7) -> torch.Tensor:
150
+ """Calculate masks IoU.
151
+
152
+ Args:
153
+ mask1 (torch.Tensor): A tensor of shape (N, n) where N is the number of ground truth objects and n is the
154
+ product of image width and height.
155
+ mask2 (torch.Tensor): A tensor of shape (M, n) where M is the number of predicted objects and n is the product
156
+ of image width and height.
157
+ eps (float, optional): A small value to avoid division by zero.
158
+
159
+ Returns:
160
+ (torch.Tensor): A tensor of shape (N, M) representing masks IoU.
161
+ """
162
+ intersection = torch.matmul(mask1, mask2.T).clamp_(0)
163
+ union = (mask1.sum(1)[:, None] + mask2.sum(1)[None]) - intersection # (area1 + area2) - intersection
164
+ return intersection / (union + eps)
165
+
166
+
167
+ def kpt_iou(
168
+ kpt1: torch.Tensor, kpt2: torch.Tensor, area: torch.Tensor, sigma: list[float], eps: float = 1e-7
169
+ ) -> torch.Tensor:
170
+ """Calculate Object Keypoint Similarity (OKS).
171
+
172
+ Args:
173
+ kpt1 (torch.Tensor): A tensor of shape (N, 17, 3) representing ground truth keypoints.
174
+ kpt2 (torch.Tensor): A tensor of shape (M, 17, 3) representing predicted keypoints.
175
+ area (torch.Tensor): A tensor of shape (N,) representing areas from ground truth.
176
+ sigma (list): A list containing 17 values representing keypoint scales.
177
+ eps (float, optional): A small value to avoid division by zero.
178
+
179
+ Returns:
180
+ (torch.Tensor): A tensor of shape (N, M) representing keypoint similarities.
181
+ """
182
+ d = (kpt1[:, None, :, 0] - kpt2[..., 0]).pow(2) + (kpt1[:, None, :, 1] - kpt2[..., 1]).pow(2) # (N, M, 17)
183
+ sigma = torch.tensor(sigma, device=kpt1.device, dtype=kpt1.dtype) # (17, )
184
+ kpt_mask = kpt1[..., 2] != 0 # (N, 17)
185
+ e = d / ((2 * sigma).pow(2) * (area[:, None, None] + eps) * 2) # from cocoeval
186
+ # e = d / ((area[None, :, None] + eps) * sigma) ** 2 / 2 # from formula
187
+ return ((-e).exp() * kpt_mask[:, None]).sum(-1) / (kpt_mask.sum(-1)[:, None] + eps)
188
+
189
+
190
+ def _get_covariance_matrix(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
191
+ """Generate covariance matrix from oriented bounding boxes.
192
+
193
+ Args:
194
+ boxes (torch.Tensor): A tensor of shape (N, 5) representing rotated bounding boxes, with xywhr format.
195
+
196
+ Returns:
197
+ (tuple[torch.Tensor, torch.Tensor, torch.Tensor]): Covariance matrix components (a, b, c) where the covariance
198
+ matrix is [[a, c], [c, b]], each of shape (N, 1).
199
+ """
200
+ # Gaussian bounding boxes, ignore the center points (the first two columns) because they are not needed here.
201
+ gbbs = torch.cat((boxes[:, 2:4].pow(2) / 12, boxes[:, 4:]), dim=-1)
202
+ a, b, c = gbbs.split(1, dim=-1)
203
+ cos = c.cos()
204
+ sin = c.sin()
205
+ cos2 = cos.pow(2)
206
+ sin2 = sin.pow(2)
207
+ return a * cos2 + b * sin2, a * sin2 + b * cos2, (a - b) * cos * sin
208
+
209
+
210
+ def probiou(obb1: torch.Tensor, obb2: torch.Tensor, CIoU: bool = False, eps: float = 1e-7) -> torch.Tensor:
211
+ """Calculate probabilistic IoU between oriented bounding boxes.
212
+
213
+ Args:
214
+ obb1 (torch.Tensor): Ground truth OBBs, shape (N, 5), format xywhr.
215
+ obb2 (torch.Tensor): Predicted OBBs, shape (N, 5), format xywhr.
216
+ CIoU (bool, optional): If True, calculate CIoU.
217
+ eps (float, optional): Small value to avoid division by zero.
218
+
219
+ Returns:
220
+ (torch.Tensor): OBB similarities, shape (N,).
221
+
222
+ Notes:
223
+ OBB format: [center_x, center_y, width, height, rotation_angle].
224
+
225
+ References:
226
+ https://arxiv.org/pdf/2106.06072v1.pdf
227
+ """
228
+ x1, y1 = obb1[..., :2].split(1, dim=-1)
229
+ x2, y2 = obb2[..., :2].split(1, dim=-1)
230
+ a1, b1, c1 = _get_covariance_matrix(obb1)
231
+ a2, b2, c2 = _get_covariance_matrix(obb2)
232
+
233
+ t1 = (
234
+ ((a1 + a2) * (y1 - y2).pow(2) + (b1 + b2) * (x1 - x2).pow(2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)
235
+ ) * 0.25
236
+ t2 = (((c1 + c2) * (x2 - x1) * (y1 - y2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)) * 0.5
237
+ t3 = (
238
+ ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2))
239
+ / (4 * ((a1 * b1 - c1.pow(2)).clamp_(0) * (a2 * b2 - c2.pow(2)).clamp_(0)).sqrt() + eps)
240
+ + eps
241
+ ).log() * 0.5
242
+ bd = (t1 + t2 + t3).clamp(eps, 100.0)
243
+ hd = (1.0 - (-bd).exp() + eps).sqrt()
244
+ iou = 1 - hd
245
+ if CIoU: # only include the wh aspect ratio part
246
+ w1, h1 = obb1[..., 2:4].split(1, dim=-1)
247
+ w2, h2 = obb2[..., 2:4].split(1, dim=-1)
248
+ v = (4 / math.pi**2) * ((w2 / h2).atan() - (w1 / h1).atan()).pow(2)
249
+ with torch.no_grad():
250
+ alpha = v / (v - iou + (1 + eps))
251
+ return iou - v * alpha # CIoU
252
+ return iou
253
+
254
+
255
+ def batch_probiou(obb1: torch.Tensor | np.ndarray, obb2: torch.Tensor | np.ndarray, eps: float = 1e-7) -> torch.Tensor:
256
+ """Calculate the probabilistic IoU between oriented bounding boxes.
257
+
258
+ Args:
259
+ obb1 (torch.Tensor | np.ndarray): A tensor of shape (N, 5) representing ground truth obbs, with xywhr format.
260
+ obb2 (torch.Tensor | np.ndarray): A tensor of shape (M, 5) representing predicted obbs, with xywhr format.
261
+ eps (float, optional): A small value to avoid division by zero.
262
+
263
+ Returns:
264
+ (torch.Tensor): A tensor of shape (N, M) representing obb similarities.
265
+
266
+ References:
267
+ https://arxiv.org/pdf/2106.06072v1.pdf
268
+ """
269
+ obb1 = torch.from_numpy(obb1) if isinstance(obb1, np.ndarray) else obb1
270
+ obb2 = torch.from_numpy(obb2) if isinstance(obb2, np.ndarray) else obb2
271
+
272
+ x1, y1 = obb1[..., :2].split(1, dim=-1)
273
+ x2, y2 = (x.squeeze(-1)[None] for x in obb2[..., :2].split(1, dim=-1))
274
+ a1, b1, c1 = _get_covariance_matrix(obb1)
275
+ a2, b2, c2 = (x.squeeze(-1)[None] for x in _get_covariance_matrix(obb2))
276
+
277
+ t1 = (
278
+ ((a1 + a2) * (y1 - y2).pow(2) + (b1 + b2) * (x1 - x2).pow(2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)
279
+ ) * 0.25
280
+ t2 = (((c1 + c2) * (x2 - x1) * (y1 - y2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)) * 0.5
281
+ t3 = (
282
+ ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2))
283
+ / (4 * ((a1 * b1 - c1.pow(2)).clamp_(0) * (a2 * b2 - c2.pow(2)).clamp_(0)).sqrt() + eps)
284
+ + eps
285
+ ).log() * 0.5
286
+ bd = (t1 + t2 + t3).clamp(eps, 100.0)
287
+ hd = (1.0 - (-bd).exp() + eps).sqrt()
288
+ return 1 - hd
289
+
290
+
291
+ def smooth_bce(eps: float = 0.1) -> tuple[float, float]:
292
+ """Compute smoothed positive and negative Binary Cross-Entropy targets.
293
+
294
+ Args:
295
+ eps (float, optional): The epsilon value for label smoothing.
296
+
297
+ Returns:
298
+ pos (float): Positive label smoothing BCE target.
299
+ neg (float): Negative label smoothing BCE target.
300
+
301
+ References:
302
+ https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
303
+ """
304
+ return 1.0 - 0.5 * eps, 0.5 * eps
305
+
306
+
307
+ class ConfusionMatrix(DataExportMixin):
308
+ """A class for calculating and updating a confusion matrix for object detection and classification tasks.
309
+
310
+ Attributes:
311
+ task (str): The type of task, either 'detect' or 'classify'.
312
+ matrix (np.ndarray): The confusion matrix, with dimensions depending on the task.
313
+ nc (int): The number of classes.
314
+ names (list[str]): The names of the classes, used as labels on the plot.
315
+ matches (dict): Contains the indices of ground truths and predictions categorized into TP, FP and FN.
316
+ """
317
+
318
+ def __init__(self, names: dict[int, str] = [], task: str = "detect", save_matches: bool = False):
319
+ """Initialize a ConfusionMatrix instance.
320
+
321
+ Args:
322
+ names (dict[int, str], optional): Names of classes, used as labels on the plot.
323
+ task (str, optional): Type of task, either 'detect' or 'classify'.
324
+ save_matches (bool, optional): Save the indices of GTs, TPs, FPs, FNs for visualization.
325
+ """
326
+ self.task = task
327
+ self.nc = len(names) # number of classes
328
+ self.matrix = np.zeros((self.nc, self.nc)) if self.task == "classify" else np.zeros((self.nc + 1, self.nc + 1))
329
+ self.names = names # name of classes
330
+ self.matches = {} if save_matches else None
331
+
332
+ def _append_matches(self, mtype: str, batch: dict[str, Any], idx: int) -> None:
333
+ """Append the matches to TP, FP, FN or GT list for the last batch.
334
+
335
+ This method updates the matches dictionary by appending specific batch data to the appropriate match type (True
336
+ Positive, False Positive, or False Negative).
337
+
338
+ Args:
339
+ mtype (str): Match type identifier ('TP', 'FP', 'FN' or 'GT').
340
+ batch (dict[str, Any]): Batch data containing detection results with keys like 'bboxes', 'cls', 'conf',
341
+ 'keypoints', 'masks'.
342
+ idx (int): Index of the specific detection to append from the batch.
343
+
344
+ Notes:
345
+ For masks, handles both overlap and non-overlap cases. When masks.max() > 1.0, it indicates
346
+ overlap_mask=True with shape (1, H, W), otherwise uses direct indexing.
347
+ """
348
+ if self.matches is None:
349
+ return
350
+ for k, v in batch.items():
351
+ if k in {"bboxes", "cls", "conf", "keypoints"}:
352
+ self.matches[mtype][k] += v[[idx]]
353
+ elif k == "masks":
354
+ # NOTE: masks.max() > 1.0 means overlap_mask=True with (1, H, W) shape
355
+ self.matches[mtype][k] += [v[0] == idx + 1] if v.max() > 1.0 else [v[idx]]
356
+
357
+ def process_cls_preds(self, preds: list[torch.Tensor], targets: list[torch.Tensor]) -> None:
358
+ """Update confusion matrix for classification task.
359
+
360
+ Args:
361
+ preds (list[N, min(nc,5)]): Predicted class labels.
362
+ targets (list[N, 1]): Ground truth class labels.
363
+ """
364
+ preds, targets = torch.cat(preds)[:, 0], torch.cat(targets)
365
+ for p, t in zip(preds.cpu().numpy(), targets.cpu().numpy()):
366
+ self.matrix[p][t] += 1
367
+
368
+ def process_batch(
369
+ self,
370
+ detections: dict[str, torch.Tensor],
371
+ batch: dict[str, Any],
372
+ conf: float = 0.25,
373
+ iou_thres: float = 0.45,
374
+ ) -> None:
375
+ """Update confusion matrix for object detection task.
376
+
377
+ Args:
378
+ detections (dict[str, torch.Tensor]): Dictionary containing detected bounding boxes and their associated
379
+ information. Should contain 'cls', 'conf', and 'bboxes' keys, where 'bboxes' can be Array[N, 4] for
380
+ regular boxes or Array[N, 5] for OBB with angle.
381
+ batch (dict[str, Any]): Batch dictionary containing ground truth data with 'bboxes' (Array[M, 4]| Array[M,
382
+ 5]) and 'cls' (Array[M]) keys, where M is the number of ground truth objects.
383
+ conf (float, optional): Confidence threshold for detections.
384
+ iou_thres (float, optional): IoU threshold for matching detections to ground truth.
385
+ """
386
+ gt_cls, gt_bboxes = batch["cls"], batch["bboxes"]
387
+ if self.matches is not None: # only if visualization is enabled
388
+ self.matches = {k: defaultdict(list) for k in {"TP", "FP", "FN", "GT"}}
389
+ for i in range(gt_cls.shape[0]):
390
+ self._append_matches("GT", batch, i) # store GT
391
+ is_obb = gt_bboxes.shape[1] == 5 # check if boxes contains angle for OBB
392
+ conf = 0.25 if conf in {None, 0.01 if is_obb else 0.001} else conf # apply 0.25 if default val conf is passed
393
+ no_pred = detections["cls"].shape[0] == 0
394
+ if gt_cls.shape[0] == 0: # Check if labels is empty
395
+ if not no_pred:
396
+ detections = {k: detections[k][detections["conf"] > conf] for k in detections}
397
+ detection_classes = detections["cls"].int().tolist()
398
+ for i, dc in enumerate(detection_classes):
399
+ self.matrix[dc, self.nc] += 1 # FP
400
+ self._append_matches("FP", detections, i)
401
+ return
402
+ if no_pred:
403
+ gt_classes = gt_cls.int().tolist()
404
+ for i, gc in enumerate(gt_classes):
405
+ self.matrix[self.nc, gc] += 1 # FN
406
+ self._append_matches("FN", batch, i)
407
+ return
408
+
409
+ detections = {k: detections[k][detections["conf"] > conf] for k in detections}
410
+ gt_classes = gt_cls.int().tolist()
411
+ detection_classes = detections["cls"].int().tolist()
412
+ bboxes = detections["bboxes"]
413
+ iou = batch_probiou(gt_bboxes, bboxes) if is_obb else box_iou(gt_bboxes, bboxes)
414
+
415
+ x = torch.where(iou > iou_thres)
416
+ if x[0].shape[0]:
417
+ matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
418
+ if x[0].shape[0] > 1:
419
+ matches = matches[matches[:, 2].argsort()[::-1]]
420
+ matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
421
+ matches = matches[matches[:, 2].argsort()[::-1]]
422
+ matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
423
+ else:
424
+ matches = np.zeros((0, 3))
425
+
426
+ n = matches.shape[0] > 0
427
+ m0, m1, _ = matches.transpose().astype(int)
428
+ for i, gc in enumerate(gt_classes):
429
+ j = m0 == i
430
+ if n and sum(j) == 1:
431
+ dc = detection_classes[m1[j].item()]
432
+ self.matrix[dc, gc] += 1 # TP if class is correct else both an FP and an FN
433
+ if dc == gc:
434
+ self._append_matches("TP", detections, m1[j].item())
435
+ else:
436
+ self._append_matches("FP", detections, m1[j].item())
437
+ self._append_matches("FN", batch, i)
438
+ else:
439
+ self.matrix[self.nc, gc] += 1 # FN
440
+ self._append_matches("FN", batch, i)
441
+
442
+ for i, dc in enumerate(detection_classes):
443
+ if not any(m1 == i):
444
+ self.matrix[dc, self.nc] += 1 # FP
445
+ self._append_matches("FP", detections, i)
446
+
447
+ def matrix(self):
448
+ """Return the confusion matrix."""
449
+ return self.matrix
450
+
451
+ def tp_fp(self) -> tuple[np.ndarray, np.ndarray]:
452
+ """Return true positives and false positives.
453
+
454
+ Returns:
455
+ tp (np.ndarray): True positives.
456
+ fp (np.ndarray): False positives.
457
+ """
458
+ tp = self.matrix.diagonal() # true positives
459
+ fp = self.matrix.sum(1) - tp # false positives
460
+ # fn = self.matrix.sum(0) - tp # false negatives (missed detections)
461
+ return (tp, fp) if self.task == "classify" else (tp[:-1], fp[:-1]) # remove background class if task=detect
462
+
463
+ def plot_matches(self, img: torch.Tensor, im_file: str, save_dir: Path) -> None:
464
+ """Plot grid of GT, TP, FP, FN for each image.
465
+
466
+ Args:
467
+ img (torch.Tensor): Image to plot onto.
468
+ im_file (str): Image filename to save visualizations.
469
+ save_dir (Path): Location to save the visualizations to.
470
+ """
471
+ if not self.matches:
472
+ return
473
+ from .ops import xyxy2xywh
474
+ from .plotting import plot_images
475
+
476
+ # Create batch of 4 (GT, TP, FP, FN)
477
+ labels = defaultdict(list)
478
+ for i, mtype in enumerate(["GT", "FP", "TP", "FN"]):
479
+ mbatch = self.matches[mtype]
480
+ if "conf" not in mbatch:
481
+ mbatch["conf"] = torch.tensor([1.0] * len(mbatch["bboxes"]), device=img.device)
482
+ mbatch["batch_idx"] = torch.ones(len(mbatch["bboxes"]), device=img.device) * i
483
+ for k in mbatch.keys():
484
+ labels[k] += mbatch[k]
485
+
486
+ labels = {k: torch.stack(v, 0) if len(v) else torch.empty(0) for k, v in labels.items()}
487
+ if self.task != "obb" and labels["bboxes"].shape[0]:
488
+ labels["bboxes"] = xyxy2xywh(labels["bboxes"])
489
+ (save_dir / "visualizations").mkdir(parents=True, exist_ok=True)
490
+ plot_images(
491
+ labels,
492
+ img.repeat(4, 1, 1, 1),
493
+ paths=["Ground Truth", "False Positives", "True Positives", "False Negatives"],
494
+ fname=save_dir / "visualizations" / Path(im_file).name,
495
+ names=self.names,
496
+ max_subplots=4,
497
+ conf_thres=0.001,
498
+ )
499
+
500
+ @TryExcept(msg="ConfusionMatrix plot failure")
501
+ @plt_settings()
502
+ def plot(self, normalize: bool = True, save_dir: str = "", on_plot=None):
503
+ """Plot the confusion matrix using matplotlib and save it to a file.
504
+
505
+ Args:
506
+ normalize (bool, optional): Whether to normalize the confusion matrix.
507
+ save_dir (str, optional): Directory where the plot will be saved.
508
+ on_plot (callable, optional): An optional callback to pass plots path and data when they are rendered.
509
+ """
510
+ import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
511
+
512
+ array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1e-9) if normalize else 1) # normalize columns
513
+ array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
514
+
515
+ fig, ax = plt.subplots(1, 1, figsize=(12, 9))
516
+ names, n = list(self.names.values()), self.nc
517
+ if self.nc >= 100: # downsample for large class count
518
+ k = max(2, self.nc // 60) # step size for downsampling, always > 1
519
+ keep_idx = slice(None, None, k) # create slice instead of array
520
+ names = names[keep_idx] # slice class names
521
+ array = array[keep_idx, :][:, keep_idx] # slice matrix rows and cols
522
+ n = (self.nc + k - 1) // k # number of retained classes
523
+ nc = nn = n if self.task == "classify" else n + 1 # adjust for background if needed
524
+ ticklabels = ([*names, "background"]) if (0 < nn < 99) and (nn == nc) else "auto"
525
+ xy_ticks = np.arange(len(ticklabels))
526
+ tick_fontsize = max(6, 15 - 0.1 * nc) # Minimum size is 6
527
+ label_fontsize = max(6, 12 - 0.1 * nc)
528
+ title_fontsize = max(6, 12 - 0.1 * nc)
529
+ btm = max(0.1, 0.25 - 0.001 * nc) # Minimum value is 0.1
530
+ with warnings.catch_warnings():
531
+ warnings.simplefilter("ignore") # suppress empty matrix RuntimeWarning: All-NaN slice encountered
532
+ im = ax.imshow(array, cmap="Blues", vmin=0.0, interpolation="none")
533
+ ax.xaxis.set_label_position("bottom")
534
+ if nc < 30: # Add score for each cell of confusion matrix
535
+ color_threshold = 0.45 * (1 if normalize else np.nanmax(array)) # text color threshold
536
+ for i, row in enumerate(array[:nc]):
537
+ for j, val in enumerate(row[:nc]):
538
+ val = array[i, j]
539
+ if np.isnan(val):
540
+ continue
541
+ ax.text(
542
+ j,
543
+ i,
544
+ f"{val:.2f}" if normalize else f"{int(val)}",
545
+ ha="center",
546
+ va="center",
547
+ fontsize=10,
548
+ color="white" if val > color_threshold else "black",
549
+ )
550
+ cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.05)
551
+ title = "Confusion Matrix" + " Normalized" * normalize
552
+ ax.set_xlabel("True", fontsize=label_fontsize, labelpad=10)
553
+ ax.set_ylabel("Predicted", fontsize=label_fontsize, labelpad=10)
554
+ ax.set_title(title, fontsize=title_fontsize, pad=20)
555
+ ax.set_xticks(xy_ticks)
556
+ ax.set_yticks(xy_ticks)
557
+ ax.tick_params(axis="x", bottom=True, top=False, labelbottom=True, labeltop=False)
558
+ ax.tick_params(axis="y", left=True, right=False, labelleft=True, labelright=False)
559
+ if ticklabels != "auto":
560
+ ax.set_xticklabels(ticklabels, fontsize=tick_fontsize, rotation=90, ha="center")
561
+ ax.set_yticklabels(ticklabels, fontsize=tick_fontsize)
562
+ for s in {"left", "right", "bottom", "top", "outline"}:
563
+ if s != "outline":
564
+ ax.spines[s].set_visible(False) # Confusion matrix plot don't have outline
565
+ cbar.ax.spines[s].set_visible(False)
566
+ fig.subplots_adjust(left=0, right=0.84, top=0.94, bottom=btm) # Adjust layout to ensure equal margins
567
+ plot_fname = Path(save_dir) / f"{title.lower().replace(' ', '_')}.png"
568
+ fig.savefig(plot_fname, dpi=250)
569
+ plt.close(fig)
570
+ if on_plot:
571
+ on_plot(plot_fname)
572
+
573
+ def print(self):
574
+ """Print the confusion matrix to the console."""
575
+ for i in range(self.matrix.shape[0]):
576
+ LOGGER.info(" ".join(map(str, self.matrix[i])))
577
+
578
+ def summary(self, normalize: bool = False, decimals: int = 5) -> list[dict[str, float]]:
579
+ """Generate a summarized representation of the confusion matrix as a list of dictionaries, with optional
580
+ normalization. This is useful for exporting the matrix to various formats such as CSV, XML, HTML, JSON,
581
+ or SQL.
582
+
583
+ Args:
584
+ normalize (bool): Whether to normalize the confusion matrix values.
585
+ decimals (int): Number of decimal places to round the output values to.
586
+
587
+ Returns:
588
+ (list[dict[str, float]]): A list of dictionaries, each representing one predicted class with corresponding
589
+ values for all actual classes.
590
+
591
+ Examples:
592
+ >>> results = model.val(data="coco8.yaml", plots=True)
593
+ >>> cm_dict = results.confusion_matrix.summary(normalize=True, decimals=5)
594
+ >>> print(cm_dict)
595
+ """
596
+ import re
597
+
598
+ names = list(self.names.values()) if self.task == "classify" else [*list(self.names.values()), "background"]
599
+ clean_names, seen = [], set()
600
+ for name in names:
601
+ clean_name = re.sub(r"[^a-zA-Z0-9_]", "_", name)
602
+ original_clean = clean_name
603
+ counter = 1
604
+ while clean_name.lower() in seen:
605
+ clean_name = f"{original_clean}_{counter}"
606
+ counter += 1
607
+ seen.add(clean_name.lower())
608
+ clean_names.append(clean_name)
609
+ array = (self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1e-9) if normalize else 1)).round(decimals)
610
+ return [
611
+ dict({"Predicted": clean_names[i]}, **{clean_names[j]: array[i, j] for j in range(len(clean_names))})
612
+ for i in range(len(clean_names))
613
+ ]
614
+
615
+
616
+ def smooth(y: np.ndarray, f: float = 0.05) -> np.ndarray:
617
+ """Box filter of fraction f."""
618
+ nf = round(len(y) * f * 2) // 2 + 1 # number of filter elements (must be odd)
619
+ p = np.ones(nf // 2) # ones padding
620
+ yp = np.concatenate((p * y[0], y, p * y[-1]), 0) # y padded
621
+ return np.convolve(yp, np.ones(nf) / nf, mode="valid") # y-smoothed
622
+
623
+
624
+ @plt_settings()
625
+ def plot_pr_curve(
626
+ px: np.ndarray,
627
+ py: np.ndarray,
628
+ ap: np.ndarray,
629
+ save_dir: Path = Path("pr_curve.png"),
630
+ names: dict[int, str] = {},
631
+ on_plot=None,
632
+ ):
633
+ """Plot precision-recall curve.
634
+
635
+ Args:
636
+ px (np.ndarray): X values for the PR curve.
637
+ py (np.ndarray): Y values for the PR curve.
638
+ ap (np.ndarray): Average precision values.
639
+ save_dir (Path, optional): Path to save the plot.
640
+ names (dict[int, str], optional): Dictionary mapping class indices to class names.
641
+ on_plot (callable, optional): Function to call after plot is saved.
642
+ """
643
+ import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
644
+
645
+ fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
646
+ py = np.stack(py, axis=1)
647
+
648
+ if 0 < len(names) < 21: # display per-class legend if < 21 classes
649
+ for i, y in enumerate(py.T):
650
+ ax.plot(px, y, linewidth=1, label=f"{names[i]} {ap[i, 0]:.3f}") # plot(recall, precision)
651
+ else:
652
+ ax.plot(px, py, linewidth=1, color="gray") # plot(recall, precision)
653
+
654
+ ax.plot(px, py.mean(1), linewidth=3, color="blue", label=f"all classes {ap[:, 0].mean():.3f} mAP@0.5")
655
+ ax.set_xlabel("Recall")
656
+ ax.set_ylabel("Precision")
657
+ ax.set_xlim(0, 1)
658
+ ax.set_ylim(0, 1)
659
+ ax.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
660
+ ax.set_title("Precision-Recall Curve")
661
+ fig.savefig(save_dir, dpi=250)
662
+ plt.close(fig)
663
+ if on_plot:
664
+ on_plot(save_dir)
665
+
666
+
667
+ @plt_settings()
668
+ def plot_mc_curve(
669
+ px: np.ndarray,
670
+ py: np.ndarray,
671
+ save_dir: Path = Path("mc_curve.png"),
672
+ names: dict[int, str] = {},
673
+ xlabel: str = "Confidence",
674
+ ylabel: str = "Metric",
675
+ on_plot=None,
676
+ ):
677
+ """Plot metric-confidence curve.
678
+
679
+ Args:
680
+ px (np.ndarray): X values for the metric-confidence curve.
681
+ py (np.ndarray): Y values for the metric-confidence curve.
682
+ save_dir (Path, optional): Path to save the plot.
683
+ names (dict[int, str], optional): Dictionary mapping class indices to class names.
684
+ xlabel (str, optional): X-axis label.
685
+ ylabel (str, optional): Y-axis label.
686
+ on_plot (callable, optional): Function to call after plot is saved.
687
+ """
688
+ import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
689
+
690
+ fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
691
+
692
+ if 0 < len(names) < 21: # display per-class legend if < 21 classes
693
+ for i, y in enumerate(py):
694
+ ax.plot(px, y, linewidth=1, label=f"{names[i]}") # plot(confidence, metric)
695
+ else:
696
+ ax.plot(px, py.T, linewidth=1, color="gray") # plot(confidence, metric)
697
+
698
+ y = smooth(py.mean(0), 0.1)
699
+ ax.plot(px, y, linewidth=3, color="blue", label=f"all classes {y.max():.2f} at {px[y.argmax()]:.3f}")
700
+ ax.set_xlabel(xlabel)
701
+ ax.set_ylabel(ylabel)
702
+ ax.set_xlim(0, 1)
703
+ ax.set_ylim(0, 1)
704
+ ax.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
705
+ ax.set_title(f"{ylabel}-Confidence Curve")
706
+ fig.savefig(save_dir, dpi=250)
707
+ plt.close(fig)
708
+ if on_plot:
709
+ on_plot(save_dir)
710
+
711
+
712
+ def compute_ap(recall: list[float], precision: list[float]) -> tuple[float, np.ndarray, np.ndarray]:
713
+ """Compute the average precision (AP) given the recall and precision curves.
714
+
715
+ Args:
716
+ recall (list): The recall curve.
717
+ precision (list): The precision curve.
718
+
719
+ Returns:
720
+ ap (float): Average precision.
721
+ mpre (np.ndarray): Precision envelope curve.
722
+ mrec (np.ndarray): Modified recall curve with sentinel values added at the beginning and end.
723
+ """
724
+ # Append sentinel values to beginning and end
725
+ mrec = np.concatenate(([0.0], recall, [1.0]))
726
+ mpre = np.concatenate(([1.0], precision, [0.0]))
727
+
728
+ # Compute the precision envelope
729
+ mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
730
+
731
+ # Integrate area under curve
732
+ method = "interp" # methods: 'continuous', 'interp'
733
+ if method == "interp":
734
+ x = np.linspace(0, 1, 101) # 101-point interp (COCO)
735
+ func = np.trapezoid if checks.check_version(np.__version__, ">=2.0") else np.trapz # np.trapz deprecated
736
+ ap = func(np.interp(x, mrec, mpre), x) # integrate
737
+ else: # 'continuous'
738
+ i = np.where(mrec[1:] != mrec[:-1])[0] # points where x-axis (recall) changes
739
+ ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
740
+
741
+ return ap, mpre, mrec
742
+
743
+
744
+ def ap_per_class(
745
+ tp: np.ndarray,
746
+ conf: np.ndarray,
747
+ pred_cls: np.ndarray,
748
+ target_cls: np.ndarray,
749
+ plot: bool = False,
750
+ on_plot=None,
751
+ save_dir: Path = Path(),
752
+ names: dict[int, str] = {},
753
+ eps: float = 1e-16,
754
+ prefix: str = "",
755
+ ) -> tuple:
756
+ """Compute the average precision per class for object detection evaluation.
757
+
758
+ Args:
759
+ tp (np.ndarray): Binary array indicating whether the detection is correct (True) or not (False).
760
+ conf (np.ndarray): Array of confidence scores of the detections.
761
+ pred_cls (np.ndarray): Array of predicted classes of the detections.
762
+ target_cls (np.ndarray): Array of true classes of the detections.
763
+ plot (bool, optional): Whether to plot PR curves or not.
764
+ on_plot (callable, optional): A callback to pass plots path and data when they are rendered.
765
+ save_dir (Path, optional): Directory to save the PR curves.
766
+ names (dict[int, str], optional): Dictionary of class names to plot PR curves.
767
+ eps (float, optional): A small value to avoid division by zero.
768
+ prefix (str, optional): A prefix string for saving the plot files.
769
+
770
+ Returns:
771
+ tp (np.ndarray): True positive counts at threshold given by max F1 metric for each class.
772
+ fp (np.ndarray): False positive counts at threshold given by max F1 metric for each class.
773
+ p (np.ndarray): Precision values at threshold given by max F1 metric for each class.
774
+ r (np.ndarray): Recall values at threshold given by max F1 metric for each class.
775
+ f1 (np.ndarray): F1-score values at threshold given by max F1 metric for each class.
776
+ ap (np.ndarray): Average precision for each class at different IoU thresholds.
777
+ unique_classes (np.ndarray): An array of unique classes that have data.
778
+ p_curve (np.ndarray): Precision curves for each class.
779
+ r_curve (np.ndarray): Recall curves for each class.
780
+ f1_curve (np.ndarray): F1-score curves for each class.
781
+ x (np.ndarray): X-axis values for the curves.
782
+ prec_values (np.ndarray): Precision values at mAP@0.5 for each class.
783
+ """
784
+ # Sort by objectness
785
+ i = np.argsort(-conf)
786
+ tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
787
+
788
+ # Find unique classes
789
+ unique_classes, nt = np.unique(target_cls, return_counts=True)
790
+ nc = unique_classes.shape[0] # number of classes, number of detections
791
+
792
+ # Create Precision-Recall curve and compute AP for each class
793
+ x, prec_values = np.linspace(0, 1, 1000), []
794
+
795
+ # Average precision, precision and recall curves
796
+ ap, p_curve, r_curve = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
797
+ for ci, c in enumerate(unique_classes):
798
+ i = pred_cls == c
799
+ n_l = nt[ci] # number of labels
800
+ n_p = i.sum() # number of predictions
801
+ if n_p == 0 or n_l == 0:
802
+ continue
803
+
804
+ # Accumulate FPs and TPs
805
+ fpc = (1 - tp[i]).cumsum(0)
806
+ tpc = tp[i].cumsum(0)
807
+
808
+ # Recall
809
+ recall = tpc / (n_l + eps) # recall curve
810
+ r_curve[ci] = np.interp(-x, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
811
+
812
+ # Precision
813
+ precision = tpc / (tpc + fpc) # precision curve
814
+ p_curve[ci] = np.interp(-x, -conf[i], precision[:, 0], left=1) # p at pr_score
815
+
816
+ # AP from recall-precision curve
817
+ for j in range(tp.shape[1]):
818
+ ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
819
+ if j == 0:
820
+ prec_values.append(np.interp(x, mrec, mpre)) # precision at mAP@0.5
821
+
822
+ prec_values = np.array(prec_values) if prec_values else np.zeros((1, 1000)) # (nc, 1000)
823
+
824
+ # Compute F1 (harmonic mean of precision and recall)
825
+ f1_curve = 2 * p_curve * r_curve / (p_curve + r_curve + eps)
826
+ names = {i: names[k] for i, k in enumerate(unique_classes) if k in names} # dict: only classes that have data
827
+ if plot:
828
+ plot_pr_curve(x, prec_values, ap, save_dir / f"{prefix}PR_curve.png", names, on_plot=on_plot)
829
+ plot_mc_curve(x, f1_curve, save_dir / f"{prefix}F1_curve.png", names, ylabel="F1", on_plot=on_plot)
830
+ plot_mc_curve(x, p_curve, save_dir / f"{prefix}P_curve.png", names, ylabel="Precision", on_plot=on_plot)
831
+ plot_mc_curve(x, r_curve, save_dir / f"{prefix}R_curve.png", names, ylabel="Recall", on_plot=on_plot)
832
+
833
+ i = smooth(f1_curve.mean(0), 0.1).argmax() # max F1 index
834
+ p, r, f1 = p_curve[:, i], r_curve[:, i], f1_curve[:, i] # max-F1 precision, recall, F1 values
835
+ tp = (r * nt).round() # true positives
836
+ fp = (tp / (p + eps) - tp).round() # false positives
837
+ return tp, fp, p, r, f1, ap, unique_classes.astype(int), p_curve, r_curve, f1_curve, x, prec_values
838
+
839
+
840
+ class Metric(SimpleClass):
841
+ """Class for computing evaluation metrics for Ultralytics YOLO models.
842
+
843
+ Attributes:
844
+ p (list): Precision for each class. Shape: (nc,).
845
+ r (list): Recall for each class. Shape: (nc,).
846
+ f1 (list): F1 score for each class. Shape: (nc,).
847
+ all_ap (list): AP scores for all classes and all IoU thresholds. Shape: (nc, 10).
848
+ ap_class_index (list): Index of class for each AP score. Shape: (nc,).
849
+ nc (int): Number of classes.
850
+
851
+ Methods:
852
+ ap50: AP at IoU threshold of 0.5 for all classes.
853
+ ap: AP at IoU thresholds from 0.5 to 0.95 for all classes.
854
+ mp: Mean precision of all classes.
855
+ mr: Mean recall of all classes.
856
+ map50: Mean AP at IoU threshold of 0.5 for all classes.
857
+ map75: Mean AP at IoU threshold of 0.75 for all classes.
858
+ map: Mean AP at IoU thresholds from 0.5 to 0.95 for all classes.
859
+ mean_results: Mean of results, returns mp, mr, map50, map.
860
+ class_result: Class-aware result, returns p[i], r[i], ap50[i], ap[i].
861
+ maps: mAP of each class.
862
+ fitness: Model fitness as a weighted combination of metrics.
863
+ update: Update metric attributes with new evaluation results.
864
+ curves: Provides a list of curves for accessing specific metrics like precision, recall, F1, etc.
865
+ curves_results: Provide a list of results for accessing specific metrics like precision, recall, F1, etc.
866
+ """
867
+
868
+ def __init__(self) -> None:
869
+ """Initialize a Metric instance for computing evaluation metrics for the YOLOv8 model."""
870
+ self.p = [] # (nc, )
871
+ self.r = [] # (nc, )
872
+ self.f1 = [] # (nc, )
873
+ self.all_ap = [] # (nc, 10)
874
+ self.ap_class_index = [] # (nc, )
875
+ self.nc = 0
876
+
877
+ @property
878
+ def ap50(self) -> np.ndarray | list:
879
+ """Return the Average Precision (AP) at an IoU threshold of 0.5 for all classes.
880
+
881
+ Returns:
882
+ (np.ndarray | list): Array of shape (nc,) with AP50 values per class, or an empty list if not available.
883
+ """
884
+ return self.all_ap[:, 0] if len(self.all_ap) else []
885
+
886
+ @property
887
+ def ap(self) -> np.ndarray | list:
888
+ """Return the Average Precision (AP) at an IoU threshold of 0.5-0.95 for all classes.
889
+
890
+ Returns:
891
+ (np.ndarray | list): Array of shape (nc,) with AP50-95 values per class, or an empty list if not available.
892
+ """
893
+ return self.all_ap.mean(1) if len(self.all_ap) else []
894
+
895
+ @property
896
+ def mp(self) -> float:
897
+ """Return the Mean Precision of all classes.
898
+
899
+ Returns:
900
+ (float): The mean precision of all classes.
901
+ """
902
+ return self.p.mean() if len(self.p) else 0.0
903
+
904
+ @property
905
+ def mr(self) -> float:
906
+ """Return the Mean Recall of all classes.
907
+
908
+ Returns:
909
+ (float): The mean recall of all classes.
910
+ """
911
+ return self.r.mean() if len(self.r) else 0.0
912
+
913
+ @property
914
+ def map50(self) -> float:
915
+ """Return the mean Average Precision (mAP) at an IoU threshold of 0.5.
916
+
917
+ Returns:
918
+ (float): The mAP at an IoU threshold of 0.5.
919
+ """
920
+ return self.all_ap[:, 0].mean() if len(self.all_ap) else 0.0
921
+
922
+ @property
923
+ def map75(self) -> float:
924
+ """Return the mean Average Precision (mAP) at an IoU threshold of 0.75.
925
+
926
+ Returns:
927
+ (float): The mAP at an IoU threshold of 0.75.
928
+ """
929
+ return self.all_ap[:, 5].mean() if len(self.all_ap) else 0.0
930
+
931
+ @property
932
+ def map(self) -> float:
933
+ """Return the mean Average Precision (mAP) over IoU thresholds of 0.5 - 0.95 in steps of 0.05.
934
+
935
+ Returns:
936
+ (float): The mAP over IoU thresholds of 0.5 - 0.95 in steps of 0.05.
937
+ """
938
+ return self.all_ap.mean() if len(self.all_ap) else 0.0
939
+
940
+ def mean_results(self) -> list[float]:
941
+ """Return mean of results, mp, mr, map50, map."""
942
+ return [self.mp, self.mr, self.map50, self.map]
943
+
944
+ def class_result(self, i: int) -> tuple[float, float, float, float]:
945
+ """Return class-aware result, p[i], r[i], ap50[i], ap[i]."""
946
+ return self.p[i], self.r[i], self.ap50[i], self.ap[i]
947
+
948
+ @property
949
+ def maps(self) -> np.ndarray:
950
+ """Return mAP of each class."""
951
+ maps = np.zeros(self.nc) + self.map
952
+ for i, c in enumerate(self.ap_class_index):
953
+ maps[c] = self.ap[i]
954
+ return maps
955
+
956
+ def fitness(self) -> float:
957
+ """Return model fitness as a weighted combination of metrics."""
958
+ w = [0.0, 0.0, 0.0, 1.0] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
959
+ return (np.nan_to_num(np.array(self.mean_results())) * w).sum()
960
+
961
+ def update(self, results: tuple):
962
+ """Update the evaluation metrics with a new set of results.
963
+
964
+ Args:
965
+ results (tuple): A tuple containing evaluation metrics:
966
+ - p (list): Precision for each class.
967
+ - r (list): Recall for each class.
968
+ - f1 (list): F1 score for each class.
969
+ - all_ap (list): AP scores for all classes and all IoU thresholds.
970
+ - ap_class_index (list): Index of class for each AP score.
971
+ - p_curve (list): Precision curve for each class.
972
+ - r_curve (list): Recall curve for each class.
973
+ - f1_curve (list): F1 curve for each class.
974
+ - px (list): X values for the curves.
975
+ - prec_values (list): Precision values for each class.
976
+ """
977
+ (
978
+ self.p,
979
+ self.r,
980
+ self.f1,
981
+ self.all_ap,
982
+ self.ap_class_index,
983
+ self.p_curve,
984
+ self.r_curve,
985
+ self.f1_curve,
986
+ self.px,
987
+ self.prec_values,
988
+ ) = results
989
+
990
+ @property
991
+ def curves(self) -> list:
992
+ """Return a list of curves for accessing specific metrics curves."""
993
+ return []
994
+
995
+ @property
996
+ def curves_results(self) -> list[list]:
997
+ """Return a list of curves for accessing specific metrics curves."""
998
+ return [
999
+ [self.px, self.prec_values, "Recall", "Precision"],
1000
+ [self.px, self.f1_curve, "Confidence", "F1"],
1001
+ [self.px, self.p_curve, "Confidence", "Precision"],
1002
+ [self.px, self.r_curve, "Confidence", "Recall"],
1003
+ ]
1004
+
1005
+
1006
+ class DetMetrics(SimpleClass, DataExportMixin):
1007
+ """Utility class for computing detection metrics such as precision, recall, and mean average precision (mAP).
1008
+
1009
+ Attributes:
1010
+ names (dict[int, str]): A dictionary of class names.
1011
+ box (Metric): An instance of the Metric class for storing detection results.
1012
+ speed (dict[str, float]): A dictionary for storing execution times of different parts of the detection process.
1013
+ task (str): The task type, set to 'detect'.
1014
+ stats (dict[str, list]): A dictionary containing lists for true positives, confidence scores, predicted classes,
1015
+ target classes, and target images.
1016
+ nt_per_class: Number of targets per class.
1017
+ nt_per_image: Number of targets per image.
1018
+
1019
+ Methods:
1020
+ update_stats: Update statistics by appending new values to existing stat collections.
1021
+ process: Process predicted results for object detection and update metrics.
1022
+ clear_stats: Clear the stored statistics.
1023
+ keys: Return a list of keys for accessing specific metrics.
1024
+ mean_results: Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95.
1025
+ class_result: Return the result of evaluating the performance of an object detection model on a specific class.
1026
+ maps: Return mean Average Precision (mAP) scores per class.
1027
+ fitness: Return the fitness of box object.
1028
+ ap_class_index: Return the average precision index per class.
1029
+ results_dict: Return dictionary of computed performance metrics and statistics.
1030
+ curves: Return a list of curves for accessing specific metrics curves.
1031
+ curves_results: Return a list of computed performance metrics and statistics.
1032
+ summary: Generate a summarized representation of per-class detection metrics as a list of dictionaries.
1033
+ """
1034
+
1035
+ def __init__(self, names: dict[int, str] = {}) -> None:
1036
+ """Initialize a DetMetrics instance with a save directory, plot flag, and class names.
1037
+
1038
+ Args:
1039
+ names (dict[int, str], optional): Dictionary of class names.
1040
+ """
1041
+ self.names = names
1042
+ self.box = Metric()
1043
+ self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0}
1044
+ self.task = "detect"
1045
+ self.stats = dict(tp=[], conf=[], pred_cls=[], target_cls=[], target_img=[])
1046
+ self.nt_per_class = None
1047
+ self.nt_per_image = None
1048
+
1049
+ def update_stats(self, stat: dict[str, Any]) -> None:
1050
+ """Update statistics by appending new values to existing stat collections.
1051
+
1052
+ Args:
1053
+ stat (dict[str, any]): Dictionary containing new statistical values to append. Keys should match existing
1054
+ keys in self.stats.
1055
+ """
1056
+ for k in self.stats.keys():
1057
+ self.stats[k].append(stat[k])
1058
+
1059
+ def process(self, save_dir: Path = Path("."), plot: bool = False, on_plot=None) -> dict[str, np.ndarray]:
1060
+ """Process predicted results for object detection and update metrics.
1061
+
1062
+ Args:
1063
+ save_dir (Path): Directory to save plots. Defaults to Path(".").
1064
+ plot (bool): Whether to plot precision-recall curves. Defaults to False.
1065
+ on_plot (callable, optional): Function to call after plots are generated. Defaults to None.
1066
+
1067
+ Returns:
1068
+ (dict[str, np.ndarray]): Dictionary containing concatenated statistics arrays.
1069
+ """
1070
+ stats = {k: np.concatenate(v, 0) for k, v in self.stats.items()} # to numpy
1071
+ if not stats:
1072
+ return stats
1073
+ results = ap_per_class(
1074
+ stats["tp"],
1075
+ stats["conf"],
1076
+ stats["pred_cls"],
1077
+ stats["target_cls"],
1078
+ plot=plot,
1079
+ save_dir=save_dir,
1080
+ names=self.names,
1081
+ on_plot=on_plot,
1082
+ prefix="Box",
1083
+ )[2:]
1084
+ self.box.nc = len(self.names)
1085
+ self.box.update(results)
1086
+ self.nt_per_class = np.bincount(stats["target_cls"].astype(int), minlength=len(self.names))
1087
+ self.nt_per_image = np.bincount(stats["target_img"].astype(int), minlength=len(self.names))
1088
+ return stats
1089
+
1090
+ def clear_stats(self):
1091
+ """Clear the stored statistics."""
1092
+ for v in self.stats.values():
1093
+ v.clear()
1094
+
1095
+ @property
1096
+ def keys(self) -> list[str]:
1097
+ """Return a list of keys for accessing specific metrics."""
1098
+ return ["metrics/precision(B)", "metrics/recall(B)", "metrics/mAP50(B)", "metrics/mAP50-95(B)"]
1099
+
1100
+ def mean_results(self) -> list[float]:
1101
+ """Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95."""
1102
+ return self.box.mean_results()
1103
+
1104
+ def class_result(self, i: int) -> tuple[float, float, float, float]:
1105
+ """Return the result of evaluating the performance of an object detection model on a specific class."""
1106
+ return self.box.class_result(i)
1107
+
1108
+ @property
1109
+ def maps(self) -> np.ndarray:
1110
+ """Return mean Average Precision (mAP) scores per class."""
1111
+ return self.box.maps
1112
+
1113
+ @property
1114
+ def fitness(self) -> float:
1115
+ """Return the fitness of box object."""
1116
+ return self.box.fitness()
1117
+
1118
+ @property
1119
+ def ap_class_index(self) -> list:
1120
+ """Return the average precision index per class."""
1121
+ return self.box.ap_class_index
1122
+
1123
+ @property
1124
+ def results_dict(self) -> dict[str, float]:
1125
+ """Return dictionary of computed performance metrics and statistics."""
1126
+ keys = [*self.keys, "fitness"]
1127
+ values = ((float(x) if hasattr(x, "item") else x) for x in ([*self.mean_results(), self.fitness]))
1128
+ return dict(zip(keys, values))
1129
+
1130
+ @property
1131
+ def curves(self) -> list[str]:
1132
+ """Return a list of curves for accessing specific metrics curves."""
1133
+ return ["Precision-Recall(B)", "F1-Confidence(B)", "Precision-Confidence(B)", "Recall-Confidence(B)"]
1134
+
1135
+ @property
1136
+ def curves_results(self) -> list[list]:
1137
+ """Return a list of computed performance metrics and statistics."""
1138
+ return self.box.curves_results
1139
+
1140
+ def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict[str, Any]]:
1141
+ """Generate a summarized representation of per-class detection metrics as a list of dictionaries. Includes
1142
+ shared scalar metrics (mAP, mAP50, mAP75) alongside precision, recall, and F1-score for each class.
1143
+
1144
+ Args:
1145
+ normalize (bool): For Detect metrics, everything is normalized by default [0-1].
1146
+ decimals (int): Number of decimal places to round the metrics values to.
1147
+
1148
+ Returns:
1149
+ (list[dict[str, Any]]): A list of dictionaries, each representing one class with corresponding metric
1150
+ values.
1151
+
1152
+ Examples:
1153
+ >>> results = model.val(data="coco8.yaml")
1154
+ >>> detection_summary = results.summary()
1155
+ >>> print(detection_summary)
1156
+ """
1157
+ per_class = {
1158
+ "Box-P": self.box.p,
1159
+ "Box-R": self.box.r,
1160
+ "Box-F1": self.box.f1,
1161
+ }
1162
+ return [
1163
+ {
1164
+ "Class": self.names[self.ap_class_index[i]],
1165
+ "Images": self.nt_per_image[self.ap_class_index[i]],
1166
+ "Instances": self.nt_per_class[self.ap_class_index[i]],
1167
+ **{k: round(v[i], decimals) for k, v in per_class.items()},
1168
+ "mAP50": round(self.class_result(i)[2], decimals),
1169
+ "mAP50-95": round(self.class_result(i)[3], decimals),
1170
+ }
1171
+ for i in range(len(per_class["Box-P"]))
1172
+ ]
1173
+
1174
+
1175
+ class SegmentMetrics(DetMetrics):
1176
+ """Calculate and aggregate detection and segmentation metrics over a given set of classes.
1177
+
1178
+ Attributes:
1179
+ names (dict[int, str]): Dictionary of class names.
1180
+ box (Metric): An instance of the Metric class for storing detection results.
1181
+ seg (Metric): An instance of the Metric class to calculate mask segmentation metrics.
1182
+ speed (dict[str, float]): A dictionary for storing execution times of different parts of the detection process.
1183
+ task (str): The task type, set to 'segment'.
1184
+ stats (dict[str, list]): A dictionary containing lists for true positives, confidence scores, predicted classes,
1185
+ target classes, and target images.
1186
+ nt_per_class: Number of targets per class.
1187
+ nt_per_image: Number of targets per image.
1188
+
1189
+ Methods:
1190
+ process: Process the detection and segmentation metrics over the given set of predictions.
1191
+ keys: Return a list of keys for accessing metrics.
1192
+ mean_results: Return the mean metrics for bounding box and segmentation results.
1193
+ class_result: Return classification results for a specified class index.
1194
+ maps: Return mAP scores for object detection and semantic segmentation models.
1195
+ fitness: Return the fitness score for both segmentation and bounding box models.
1196
+ curves: Return a list of curves for accessing specific metrics curves.
1197
+ curves_results: Provide a list of computed performance metrics and statistics.
1198
+ summary: Generate a summarized representation of per-class segmentation metrics as a list of dictionaries.
1199
+ """
1200
+
1201
+ def __init__(self, names: dict[int, str] = {}) -> None:
1202
+ """Initialize a SegmentMetrics instance with a save directory, plot flag, and class names.
1203
+
1204
+ Args:
1205
+ names (dict[int, str], optional): Dictionary of class names.
1206
+ """
1207
+ DetMetrics.__init__(self, names)
1208
+ self.seg = Metric()
1209
+ self.task = "segment"
1210
+ self.stats["tp_m"] = [] # add additional stats for masks
1211
+
1212
+ def process(self, save_dir: Path = Path("."), plot: bool = False, on_plot=None) -> dict[str, np.ndarray]:
1213
+ """Process the detection and segmentation metrics over the given set of predictions.
1214
+
1215
+ Args:
1216
+ save_dir (Path): Directory to save plots. Defaults to Path(".").
1217
+ plot (bool): Whether to plot precision-recall curves. Defaults to False.
1218
+ on_plot (callable, optional): Function to call after plots are generated. Defaults to None.
1219
+
1220
+ Returns:
1221
+ (dict[str, np.ndarray]): Dictionary containing concatenated statistics arrays.
1222
+ """
1223
+ stats = DetMetrics.process(self, save_dir, plot, on_plot=on_plot) # process box stats
1224
+ results_mask = ap_per_class(
1225
+ stats["tp_m"],
1226
+ stats["conf"],
1227
+ stats["pred_cls"],
1228
+ stats["target_cls"],
1229
+ plot=plot,
1230
+ on_plot=on_plot,
1231
+ save_dir=save_dir,
1232
+ names=self.names,
1233
+ prefix="Mask",
1234
+ )[2:]
1235
+ self.seg.nc = len(self.names)
1236
+ self.seg.update(results_mask)
1237
+ return stats
1238
+
1239
+ @property
1240
+ def keys(self) -> list[str]:
1241
+ """Return a list of keys for accessing metrics."""
1242
+ return [
1243
+ *DetMetrics.keys.fget(self),
1244
+ "metrics/precision(M)",
1245
+ "metrics/recall(M)",
1246
+ "metrics/mAP50(M)",
1247
+ "metrics/mAP50-95(M)",
1248
+ ]
1249
+
1250
+ def mean_results(self) -> list[float]:
1251
+ """Return the mean metrics for bounding box and segmentation results."""
1252
+ return DetMetrics.mean_results(self) + self.seg.mean_results()
1253
+
1254
+ def class_result(self, i: int) -> list[float]:
1255
+ """Return classification results for a specified class index."""
1256
+ return DetMetrics.class_result(self, i) + self.seg.class_result(i)
1257
+
1258
+ @property
1259
+ def maps(self) -> np.ndarray:
1260
+ """Return mAP scores for object detection and semantic segmentation models."""
1261
+ return DetMetrics.maps.fget(self) + self.seg.maps
1262
+
1263
+ @property
1264
+ def fitness(self) -> float:
1265
+ """Return the fitness score for both segmentation and bounding box models."""
1266
+ return self.seg.fitness() + DetMetrics.fitness.fget(self)
1267
+
1268
+ @property
1269
+ def curves(self) -> list[str]:
1270
+ """Return a list of curves for accessing specific metrics curves."""
1271
+ return [
1272
+ *DetMetrics.curves.fget(self),
1273
+ "Precision-Recall(M)",
1274
+ "F1-Confidence(M)",
1275
+ "Precision-Confidence(M)",
1276
+ "Recall-Confidence(M)",
1277
+ ]
1278
+
1279
+ @property
1280
+ def curves_results(self) -> list[list]:
1281
+ """Return a list of computed performance metrics and statistics."""
1282
+ return DetMetrics.curves_results.fget(self) + self.seg.curves_results
1283
+
1284
+ def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict[str, Any]]:
1285
+ """Generate a summarized representation of per-class segmentation metrics as a list of dictionaries. Includes
1286
+ both box and mask scalar metrics (mAP, mAP50, mAP75) alongside precision, recall, and F1-score for
1287
+ each class.
1288
+
1289
+ Args:
1290
+ normalize (bool): For Segment metrics, everything is normalized by default [0-1].
1291
+ decimals (int): Number of decimal places to round the metrics values to.
1292
+
1293
+ Returns:
1294
+ (list[dict[str, Any]]): A list of dictionaries, each representing one class with corresponding metric
1295
+ values.
1296
+
1297
+ Examples:
1298
+ >>> results = model.val(data="coco8-seg.yaml")
1299
+ >>> seg_summary = results.summary(decimals=4)
1300
+ >>> print(seg_summary)
1301
+ """
1302
+ per_class = {
1303
+ "Mask-P": self.seg.p,
1304
+ "Mask-R": self.seg.r,
1305
+ "Mask-F1": self.seg.f1,
1306
+ }
1307
+ summary = DetMetrics.summary(self, normalize, decimals) # get box summary
1308
+ for i, s in enumerate(summary):
1309
+ s.update({**{k: round(v[i], decimals) for k, v in per_class.items()}})
1310
+ return summary
1311
+
1312
+
1313
+ class PoseMetrics(DetMetrics):
1314
+ """Calculate and aggregate detection and pose metrics over a given set of classes.
1315
+
1316
+ Attributes:
1317
+ names (dict[int, str]): Dictionary of class names.
1318
+ pose (Metric): An instance of the Metric class to calculate pose metrics.
1319
+ box (Metric): An instance of the Metric class for storing detection results.
1320
+ speed (dict[str, float]): A dictionary for storing execution times of different parts of the detection process.
1321
+ task (str): The task type, set to 'pose'.
1322
+ stats (dict[str, list]): A dictionary containing lists for true positives, confidence scores, predicted classes,
1323
+ target classes, and target images.
1324
+ nt_per_class: Number of targets per class.
1325
+ nt_per_image: Number of targets per image.
1326
+
1327
+ Methods:
1328
+ process: Process the detection and pose metrics over the given set of predictions. R
1329
+ keys: Return a list of keys for accessing metrics.
1330
+ mean_results: Return the mean results of box and pose.
1331
+ class_result: Return the class-wise detection results for a specific class i.
1332
+ maps: Return the mean average precision (mAP) per class for both box and pose detections.
1333
+ fitness: Return combined fitness score for pose and box detection.
1334
+ curves: Return a list of curves for accessing specific metrics curves.
1335
+ curves_results: Provide a list of computed performance metrics and statistics.
1336
+ summary: Generate a summarized representation of per-class pose metrics as a list of dictionaries.
1337
+ """
1338
+
1339
+ def __init__(self, names: dict[int, str] = {}) -> None:
1340
+ """Initialize the PoseMetrics class with directory path, class names, and plotting options.
1341
+
1342
+ Args:
1343
+ names (dict[int, str], optional): Dictionary of class names.
1344
+ """
1345
+ super().__init__(names)
1346
+ self.pose = Metric()
1347
+ self.task = "pose"
1348
+ self.stats["tp_p"] = [] # add additional stats for pose
1349
+
1350
+ def process(self, save_dir: Path = Path("."), plot: bool = False, on_plot=None) -> dict[str, np.ndarray]:
1351
+ """Process the detection and pose metrics over the given set of predictions.
1352
+
1353
+ Args:
1354
+ save_dir (Path): Directory to save plots. Defaults to Path(".").
1355
+ plot (bool): Whether to plot precision-recall curves. Defaults to False.
1356
+ on_plot (callable, optional): Function to call after plots are generated.
1357
+
1358
+ Returns:
1359
+ (dict[str, np.ndarray]): Dictionary containing concatenated statistics arrays.
1360
+ """
1361
+ stats = DetMetrics.process(self, save_dir, plot, on_plot=on_plot) # process box stats
1362
+ results_pose = ap_per_class(
1363
+ stats["tp_p"],
1364
+ stats["conf"],
1365
+ stats["pred_cls"],
1366
+ stats["target_cls"],
1367
+ plot=plot,
1368
+ on_plot=on_plot,
1369
+ save_dir=save_dir,
1370
+ names=self.names,
1371
+ prefix="Pose",
1372
+ )[2:]
1373
+ self.pose.nc = len(self.names)
1374
+ self.pose.update(results_pose)
1375
+ return stats
1376
+
1377
+ @property
1378
+ def keys(self) -> list[str]:
1379
+ """Return a list of evaluation metric keys."""
1380
+ return [
1381
+ *DetMetrics.keys.fget(self),
1382
+ "metrics/precision(P)",
1383
+ "metrics/recall(P)",
1384
+ "metrics/mAP50(P)",
1385
+ "metrics/mAP50-95(P)",
1386
+ ]
1387
+
1388
+ def mean_results(self) -> list[float]:
1389
+ """Return the mean results of box and pose."""
1390
+ return DetMetrics.mean_results(self) + self.pose.mean_results()
1391
+
1392
+ def class_result(self, i: int) -> list[float]:
1393
+ """Return the class-wise detection results for a specific class i."""
1394
+ return DetMetrics.class_result(self, i) + self.pose.class_result(i)
1395
+
1396
+ @property
1397
+ def maps(self) -> np.ndarray:
1398
+ """Return the mean average precision (mAP) per class for both box and pose detections."""
1399
+ return DetMetrics.maps.fget(self) + self.pose.maps
1400
+
1401
+ @property
1402
+ def fitness(self) -> float:
1403
+ """Return combined fitness score for pose and box detection."""
1404
+ return self.pose.fitness() + DetMetrics.fitness.fget(self)
1405
+
1406
+ @property
1407
+ def curves(self) -> list[str]:
1408
+ """Return a list of curves for accessing specific metrics curves."""
1409
+ return [
1410
+ *DetMetrics.curves.fget(self),
1411
+ "Precision-Recall(B)",
1412
+ "F1-Confidence(B)",
1413
+ "Precision-Confidence(B)",
1414
+ "Recall-Confidence(B)",
1415
+ "Precision-Recall(P)",
1416
+ "F1-Confidence(P)",
1417
+ "Precision-Confidence(P)",
1418
+ "Recall-Confidence(P)",
1419
+ ]
1420
+
1421
+ @property
1422
+ def curves_results(self) -> list[list]:
1423
+ """Return a list of computed performance metrics and statistics."""
1424
+ return DetMetrics.curves_results.fget(self) + self.pose.curves_results
1425
+
1426
+ def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict[str, Any]]:
1427
+ """Generate a summarized representation of per-class pose metrics as a list of dictionaries. Includes both box
1428
+ and pose scalar metrics (mAP, mAP50, mAP75) alongside precision, recall, and F1-score for each class.
1429
+
1430
+ Args:
1431
+ normalize (bool): For Pose metrics, everything is normalized by default [0-1].
1432
+ decimals (int): Number of decimal places to round the metrics values to.
1433
+
1434
+ Returns:
1435
+ (list[dict[str, Any]]): A list of dictionaries, each representing one class with corresponding metric
1436
+ values.
1437
+
1438
+ Examples:
1439
+ >>> results = model.val(data="coco8-pose.yaml")
1440
+ >>> pose_summary = results.summary(decimals=4)
1441
+ >>> print(pose_summary)
1442
+ """
1443
+ per_class = {
1444
+ "Pose-P": self.pose.p,
1445
+ "Pose-R": self.pose.r,
1446
+ "Pose-F1": self.pose.f1,
1447
+ }
1448
+ summary = DetMetrics.summary(self, normalize, decimals) # get box summary
1449
+ for i, s in enumerate(summary):
1450
+ s.update({**{k: round(v[i], decimals) for k, v in per_class.items()}})
1451
+ return summary
1452
+
1453
+
1454
+ class ClassifyMetrics(SimpleClass, DataExportMixin):
1455
+ """Class for computing classification metrics including top-1 and top-5 accuracy.
1456
+
1457
+ Attributes:
1458
+ top1 (float): The top-1 accuracy.
1459
+ top5 (float): The top-5 accuracy.
1460
+ speed (dict): A dictionary containing the time taken for each step in the pipeline.
1461
+ task (str): The task type, set to 'classify'.
1462
+
1463
+ Methods:
1464
+ process: Process target classes and predicted classes to compute metrics.
1465
+ fitness: Return mean of top-1 and top-5 accuracies as fitness score.
1466
+ results_dict: Return a dictionary with model's performance metrics and fitness score.
1467
+ keys: Return a list of keys for the results_dict property.
1468
+ curves: Return a list of curves for accessing specific metrics curves.
1469
+ curves_results: Provide a list of computed performance metrics and statistics.
1470
+ summary: Generate a single-row summary of classification metrics (Top-1 and Top-5 accuracy).
1471
+ """
1472
+
1473
+ def __init__(self) -> None:
1474
+ """Initialize a ClassifyMetrics instance."""
1475
+ self.top1 = 0
1476
+ self.top5 = 0
1477
+ self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0}
1478
+ self.task = "classify"
1479
+
1480
+ def process(self, targets: torch.Tensor, pred: torch.Tensor):
1481
+ """Process target classes and predicted classes to compute metrics.
1482
+
1483
+ Args:
1484
+ targets (torch.Tensor): Target classes.
1485
+ pred (torch.Tensor): Predicted classes.
1486
+ """
1487
+ pred, targets = torch.cat(pred), torch.cat(targets)
1488
+ correct = (targets[:, None] == pred).float()
1489
+ acc = torch.stack((correct[:, 0], correct.max(1).values), dim=1) # (top1, top5) accuracy
1490
+ self.top1, self.top5 = acc.mean(0).tolist()
1491
+
1492
+ @property
1493
+ def fitness(self) -> float:
1494
+ """Return mean of top-1 and top-5 accuracies as fitness score."""
1495
+ return (self.top1 + self.top5) / 2
1496
+
1497
+ @property
1498
+ def results_dict(self) -> dict[str, float]:
1499
+ """Return a dictionary with model's performance metrics and fitness score."""
1500
+ return dict(zip([*self.keys, "fitness"], [self.top1, self.top5, self.fitness]))
1501
+
1502
+ @property
1503
+ def keys(self) -> list[str]:
1504
+ """Return a list of keys for the results_dict property."""
1505
+ return ["metrics/accuracy_top1", "metrics/accuracy_top5"]
1506
+
1507
+ @property
1508
+ def curves(self) -> list:
1509
+ """Return a list of curves for accessing specific metrics curves."""
1510
+ return []
1511
+
1512
+ @property
1513
+ def curves_results(self) -> list:
1514
+ """Return a list of curves for accessing specific metrics curves."""
1515
+ return []
1516
+
1517
+ def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict[str, float]]:
1518
+ """Generate a single-row summary of classification metrics (Top-1 and Top-5 accuracy).
1519
+
1520
+ Args:
1521
+ normalize (bool): For Classify metrics, everything is normalized by default [0-1].
1522
+ decimals (int): Number of decimal places to round the metrics values to.
1523
+
1524
+ Returns:
1525
+ (list[dict[str, float]]): A list with one dictionary containing Top-1 and Top-5 classification accuracy.
1526
+
1527
+ Examples:
1528
+ >>> results = model.val(data="imagenet10")
1529
+ >>> classify_summary = results.summary(decimals=4)
1530
+ >>> print(classify_summary)
1531
+ """
1532
+ return [{"top1_acc": round(self.top1, decimals), "top5_acc": round(self.top5, decimals)}]
1533
+
1534
+
1535
+ class OBBMetrics(DetMetrics):
1536
+ """Metrics for evaluating oriented bounding box (OBB) detection.
1537
+
1538
+ Attributes:
1539
+ names (dict[int, str]): Dictionary of class names.
1540
+ box (Metric): An instance of the Metric class for storing detection results.
1541
+ speed (dict[str, float]): A dictionary for storing execution times of different parts of the detection process.
1542
+ task (str): The task type, set to 'obb'.
1543
+ stats (dict[str, list]): A dictionary containing lists for true positives, confidence scores, predicted classes,
1544
+ target classes, and target images.
1545
+ nt_per_class: Number of targets per class.
1546
+ nt_per_image: Number of targets per image.
1547
+
1548
+ References:
1549
+ https://arxiv.org/pdf/2106.06072.pdf
1550
+ """
1551
+
1552
+ def __init__(self, names: dict[int, str] = {}) -> None:
1553
+ """Initialize an OBBMetrics instance with directory, plotting, and class names.
1554
+
1555
+ Args:
1556
+ names (dict[int, str], optional): Dictionary of class names.
1557
+ """
1558
+ DetMetrics.__init__(self, names)
1559
+ # TODO: probably remove task as well
1560
+ self.task = "obb"