results.py 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
  2. """
  3. Ultralytics Results, Boxes and Masks classes for handling inference results.
  4. Usage: See https://docs.ultralytics.com/modes/predict/
  5. """
  6. from copy import deepcopy
  7. from functools import lru_cache
  8. from pathlib import Path
  9. import numpy as np
  10. import torch
  11. from ultralytics.data.augment import LetterBox
  12. from ultralytics.utils import LOGGER, SimpleClass, ops
  13. from ultralytics.utils.checks import check_requirements
  14. from ultralytics.utils.plotting import Annotator, colors, save_one_box
  15. from ultralytics.utils.torch_utils import smart_inference_mode
  16. class BaseTensor(SimpleClass):
  17. """
  18. Base tensor class with additional methods for easy manipulation and device handling.
  19. Attributes:
  20. data (torch.Tensor | np.ndarray): Prediction data such as bounding boxes, masks, or keypoints.
  21. orig_shape (Tuple[int, int]): Original shape of the image, typically in the format (height, width).
  22. Methods:
  23. cpu: Return a copy of the tensor stored in CPU memory.
  24. numpy: Returns a copy of the tensor as a numpy array.
  25. cuda: Moves the tensor to GPU memory, returning a new instance if necessary.
  26. to: Return a copy of the tensor with the specified device and dtype.
  27. Examples:
  28. >>> import torch
  29. >>> data = torch.tensor([[1, 2, 3], [4, 5, 6]])
  30. >>> orig_shape = (720, 1280)
  31. >>> base_tensor = BaseTensor(data, orig_shape)
  32. >>> cpu_tensor = base_tensor.cpu()
  33. >>> numpy_array = base_tensor.numpy()
  34. >>> gpu_tensor = base_tensor.cuda()
  35. """
  36. def __init__(self, data, orig_shape) -> None:
  37. """
  38. Initialize BaseTensor with prediction data and the original shape of the image.
  39. Args:
  40. data (torch.Tensor | np.ndarray): Prediction data such as bounding boxes, masks, or keypoints.
  41. orig_shape (Tuple[int, int]): Original shape of the image in (height, width) format.
  42. Examples:
  43. >>> import torch
  44. >>> data = torch.tensor([[1, 2, 3], [4, 5, 6]])
  45. >>> orig_shape = (720, 1280)
  46. >>> base_tensor = BaseTensor(data, orig_shape)
  47. """
  48. assert isinstance(data, (torch.Tensor, np.ndarray)), "data must be torch.Tensor or np.ndarray"
  49. self.data = data
  50. self.orig_shape = orig_shape
  51. @property
  52. def shape(self):
  53. """
  54. Returns the shape of the underlying data tensor.
  55. Returns:
  56. (Tuple[int, ...]): The shape of the data tensor.
  57. Examples:
  58. >>> data = torch.rand(100, 4)
  59. >>> base_tensor = BaseTensor(data, orig_shape=(720, 1280))
  60. >>> print(base_tensor.shape)
  61. (100, 4)
  62. """
  63. return self.data.shape
  64. def cpu(self):
  65. """
  66. Returns a copy of the tensor stored in CPU memory.
  67. Returns:
  68. (BaseTensor): A new BaseTensor object with the data tensor moved to CPU memory.
  69. Examples:
  70. >>> data = torch.tensor([[1, 2, 3], [4, 5, 6]]).cuda()
  71. >>> base_tensor = BaseTensor(data, orig_shape=(720, 1280))
  72. >>> cpu_tensor = base_tensor.cpu()
  73. >>> isinstance(cpu_tensor, BaseTensor)
  74. True
  75. >>> cpu_tensor.data.device
  76. device(type='cpu')
  77. """
  78. return self if isinstance(self.data, np.ndarray) else self.__class__(self.data.cpu(), self.orig_shape)
  79. def numpy(self):
  80. """
  81. Returns a copy of the tensor as a numpy array.
  82. Returns:
  83. (np.ndarray): A numpy array containing the same data as the original tensor.
  84. Examples:
  85. >>> data = torch.tensor([[1, 2, 3], [4, 5, 6]])
  86. >>> orig_shape = (720, 1280)
  87. >>> base_tensor = BaseTensor(data, orig_shape)
  88. >>> numpy_array = base_tensor.numpy()
  89. >>> print(type(numpy_array))
  90. <class 'numpy.ndarray'>
  91. """
  92. return self if isinstance(self.data, np.ndarray) else self.__class__(self.data.numpy(), self.orig_shape)
  93. def cuda(self):
  94. """
  95. Moves the tensor to GPU memory.
  96. Returns:
  97. (BaseTensor): A new BaseTensor instance with the data moved to GPU memory if it's not already a
  98. numpy array, otherwise returns self.
  99. Examples:
  100. >>> import torch
  101. >>> from ultralytics.engine.results import BaseTensor
  102. >>> data = torch.tensor([[1, 2, 3], [4, 5, 6]])
  103. >>> base_tensor = BaseTensor(data, orig_shape=(720, 1280))
  104. >>> gpu_tensor = base_tensor.cuda()
  105. >>> print(gpu_tensor.data.device)
  106. cuda:0
  107. """
  108. return self.__class__(torch.as_tensor(self.data).cuda(), self.orig_shape)
  109. def to(self, *args, **kwargs):
  110. """
  111. Return a copy of the tensor with the specified device and dtype.
  112. Args:
  113. *args (Any): Variable length argument list to be passed to torch.Tensor.to().
  114. **kwargs (Any): Arbitrary keyword arguments to be passed to torch.Tensor.to().
  115. Returns:
  116. (BaseTensor): A new BaseTensor instance with the data moved to the specified device and/or dtype.
  117. Examples:
  118. >>> base_tensor = BaseTensor(torch.randn(3, 4), orig_shape=(480, 640))
  119. >>> cuda_tensor = base_tensor.to("cuda")
  120. >>> float16_tensor = base_tensor.to(dtype=torch.float16)
  121. """
  122. return self.__class__(torch.as_tensor(self.data).to(*args, **kwargs), self.orig_shape)
  123. def __len__(self): # override len(results)
  124. """
  125. Returns the length of the underlying data tensor.
  126. Returns:
  127. (int): The number of elements in the first dimension of the data tensor.
  128. Examples:
  129. >>> data = torch.tensor([[1, 2, 3], [4, 5, 6]])
  130. >>> base_tensor = BaseTensor(data, orig_shape=(720, 1280))
  131. >>> len(base_tensor)
  132. 2
  133. """
  134. return len(self.data)
  135. def __getitem__(self, idx):
  136. """
  137. Returns a new BaseTensor instance containing the specified indexed elements of the data tensor.
  138. Args:
  139. idx (int | List[int] | torch.Tensor): Index or indices to select from the data tensor.
  140. Returns:
  141. (BaseTensor): A new BaseTensor instance containing the indexed data.
  142. Examples:
  143. >>> data = torch.tensor([[1, 2, 3], [4, 5, 6]])
  144. >>> base_tensor = BaseTensor(data, orig_shape=(720, 1280))
  145. >>> result = base_tensor[0] # Select the first row
  146. >>> print(result.data)
  147. tensor([1, 2, 3])
  148. """
  149. return self.__class__(self.data[idx], self.orig_shape)
  150. class Results(SimpleClass):
  151. """
  152. A class for storing and manipulating inference results.
  153. This class encapsulates the functionality for handling detection, segmentation, pose estimation,
  154. and classification results from YOLO models.
  155. Attributes:
  156. orig_img (numpy.ndarray): Original image as a numpy array.
  157. orig_shape (Tuple[int, int]): Original image shape in (height, width) format.
  158. boxes (Boxes | None): Object containing detection bounding boxes.
  159. masks (Masks | None): Object containing detection masks.
  160. probs (Probs | None): Object containing class probabilities for classification tasks.
  161. keypoints (Keypoints | None): Object containing detected keypoints for each object.
  162. obb (OBB | None): Object containing oriented bounding boxes.
  163. speed (Dict[str, float | None]): Dictionary of preprocess, inference, and postprocess speeds.
  164. names (Dict[int, str]): Dictionary mapping class IDs to class names.
  165. path (str): Path to the image file.
  166. _keys (Tuple[str, ...]): Tuple of attribute names for internal use.
  167. Methods:
  168. update: Updates object attributes with new detection results.
  169. cpu: Returns a copy of the Results object with all tensors on CPU memory.
  170. numpy: Returns a copy of the Results object with all tensors as numpy arrays.
  171. cuda: Returns a copy of the Results object with all tensors on GPU memory.
  172. to: Returns a copy of the Results object with tensors on a specified device and dtype.
  173. new: Returns a new Results object with the same image, path, and names.
  174. plot: Plots detection results on an input image, returning an annotated image.
  175. show: Shows annotated results on screen.
  176. save: Saves annotated results to file.
  177. verbose: Returns a log string for each task, detailing detections and classifications.
  178. save_txt: Saves detection results to a text file.
  179. save_crop: Saves cropped detection images.
  180. tojson: Converts detection results to JSON format.
  181. Examples:
  182. >>> results = model("path/to/image.jpg")
  183. >>> for result in results:
  184. ... print(result.boxes) # Print detection boxes
  185. ... result.show() # Display the annotated image
  186. ... result.save(filename="result.jpg") # Save annotated image
  187. """
  188. def __init__(
  189. self, orig_img, path, names, boxes=None, masks=None, probs=None, keypoints=None, obb=None, speed=None
  190. ) -> None:
  191. """
  192. Initialize the Results class for storing and manipulating inference results.
  193. Args:
  194. orig_img (numpy.ndarray): The original image as a numpy array.
  195. path (str): The path to the image file.
  196. names (Dict): A dictionary of class names.
  197. boxes (torch.Tensor | None): A 2D tensor of bounding box coordinates for each detection.
  198. masks (torch.Tensor | None): A 3D tensor of detection masks, where each mask is a binary image.
  199. probs (torch.Tensor | None): A 1D tensor of probabilities of each class for classification task.
  200. keypoints (torch.Tensor | None): A 2D tensor of keypoint coordinates for each detection.
  201. obb (torch.Tensor | None): A 2D tensor of oriented bounding box coordinates for each detection.
  202. speed (Dict | None): A dictionary containing preprocess, inference, and postprocess speeds (ms/image).
  203. Examples:
  204. >>> results = model("path/to/image.jpg")
  205. >>> result = results[0] # Get the first result
  206. >>> boxes = result.boxes # Get the boxes for the first result
  207. >>> masks = result.masks # Get the masks for the first result
  208. Notes:
  209. For the default pose model, keypoint indices for human body pose estimation are:
  210. 0: Nose, 1: Left Eye, 2: Right Eye, 3: Left Ear, 4: Right Ear
  211. 5: Left Shoulder, 6: Right Shoulder, 7: Left Elbow, 8: Right Elbow
  212. 9: Left Wrist, 10: Right Wrist, 11: Left Hip, 12: Right Hip
  213. 13: Left Knee, 14: Right Knee, 15: Left Ankle, 16: Right Ankle
  214. """
  215. self.orig_img = orig_img
  216. self.orig_shape = orig_img.shape[:2]
  217. self.boxes = Boxes(boxes, self.orig_shape) if boxes is not None else None # native size boxes
  218. self.masks = Masks(masks, self.orig_shape) if masks is not None else None # native size or imgsz masks
  219. self.probs = Probs(probs) if probs is not None else None
  220. self.keypoints = Keypoints(keypoints, self.orig_shape) if keypoints is not None else None
  221. self.obb = OBB(obb, self.orig_shape) if obb is not None else None
  222. self.speed = speed if speed is not None else {"preprocess": None, "inference": None, "postprocess": None}
  223. self.names = names
  224. self.path = path
  225. self.save_dir = None
  226. self._keys = "boxes", "masks", "probs", "keypoints", "obb"
  227. def __getitem__(self, idx):
  228. """
  229. Return a Results object for a specific index of inference results.
  230. Args:
  231. idx (int | slice): Index or slice to retrieve from the Results object.
  232. Returns:
  233. (Results): A new Results object containing the specified subset of inference results.
  234. Examples:
  235. >>> results = model("path/to/image.jpg") # Perform inference
  236. >>> single_result = results[0] # Get the first result
  237. >>> subset_results = results[1:4] # Get a slice of results
  238. """
  239. return self._apply("__getitem__", idx)
  240. def __len__(self):
  241. """
  242. Return the number of detections in the Results object.
  243. Returns:
  244. (int): The number of detections, determined by the length of the first non-empty attribute
  245. (boxes, masks, probs, keypoints, or obb).
  246. Examples:
  247. >>> results = Results(orig_img, path, names, boxes=torch.rand(5, 4))
  248. >>> len(results)
  249. 5
  250. """
  251. for k in self._keys:
  252. v = getattr(self, k)
  253. if v is not None:
  254. return len(v)
  255. def update(self, boxes=None, masks=None, probs=None, obb=None):
  256. """
  257. Updates the Results object with new detection data.
  258. This method allows updating the boxes, masks, probabilities, and oriented bounding boxes (OBB) of the
  259. Results object. It ensures that boxes are clipped to the original image shape.
  260. Args:
  261. boxes (torch.Tensor | None): A tensor of shape (N, 6) containing bounding box coordinates and
  262. confidence scores. The format is (x1, y1, x2, y2, conf, class).
  263. masks (torch.Tensor | None): A tensor of shape (N, H, W) containing segmentation masks.
  264. probs (torch.Tensor | None): A tensor of shape (num_classes,) containing class probabilities.
  265. obb (torch.Tensor | None): A tensor of shape (N, 5) containing oriented bounding box coordinates.
  266. Examples:
  267. >>> results = model("image.jpg")
  268. >>> new_boxes = torch.tensor([[100, 100, 200, 200, 0.9, 0]])
  269. >>> results[0].update(boxes=new_boxes)
  270. """
  271. if boxes is not None:
  272. self.boxes = Boxes(ops.clip_boxes(boxes, self.orig_shape), self.orig_shape)
  273. if masks is not None:
  274. self.masks = Masks(masks, self.orig_shape)
  275. if probs is not None:
  276. self.probs = probs
  277. if obb is not None:
  278. self.obb = OBB(obb, self.orig_shape)
  279. def _apply(self, fn, *args, **kwargs):
  280. """
  281. Applies a function to all non-empty attributes and returns a new Results object with modified attributes.
  282. This method is internally called by methods like .to(), .cuda(), .cpu(), etc.
  283. Args:
  284. fn (str): The name of the function to apply.
  285. *args (Any): Variable length argument list to pass to the function.
  286. **kwargs (Any): Arbitrary keyword arguments to pass to the function.
  287. Returns:
  288. (Results): A new Results object with attributes modified by the applied function.
  289. Examples:
  290. >>> results = model("path/to/image.jpg")
  291. >>> for result in results:
  292. ... result_cuda = result.cuda()
  293. ... result_cpu = result.cpu()
  294. """
  295. r = self.new()
  296. for k in self._keys:
  297. v = getattr(self, k)
  298. if v is not None:
  299. setattr(r, k, getattr(v, fn)(*args, **kwargs))
  300. return r
  301. def cpu(self):
  302. """
  303. Returns a copy of the Results object with all its tensors moved to CPU memory.
  304. This method creates a new Results object with all tensor attributes (boxes, masks, probs, keypoints, obb)
  305. transferred to CPU memory. It's useful for moving data from GPU to CPU for further processing or saving.
  306. Returns:
  307. (Results): A new Results object with all tensor attributes on CPU memory.
  308. Examples:
  309. >>> results = model("path/to/image.jpg") # Perform inference
  310. >>> cpu_result = results[0].cpu() # Move the first result to CPU
  311. >>> print(cpu_result.boxes.device) # Output: cpu
  312. """
  313. return self._apply("cpu")
  314. def numpy(self):
  315. """
  316. Converts all tensors in the Results object to numpy arrays.
  317. Returns:
  318. (Results): A new Results object with all tensors converted to numpy arrays.
  319. Examples:
  320. >>> results = model("path/to/image.jpg")
  321. >>> numpy_result = results[0].numpy()
  322. >>> type(numpy_result.boxes.data)
  323. <class 'numpy.ndarray'>
  324. Notes:
  325. This method creates a new Results object, leaving the original unchanged. It's useful for
  326. interoperability with numpy-based libraries or when CPU-based operations are required.
  327. """
  328. return self._apply("numpy")
  329. def cuda(self):
  330. """
  331. Moves all tensors in the Results object to GPU memory.
  332. Returns:
  333. (Results): A new Results object with all tensors moved to CUDA device.
  334. Examples:
  335. >>> results = model("path/to/image.jpg")
  336. >>> cuda_results = results[0].cuda() # Move first result to GPU
  337. >>> for result in results:
  338. ... result_cuda = result.cuda() # Move each result to GPU
  339. """
  340. return self._apply("cuda")
  341. def to(self, *args, **kwargs):
  342. """
  343. Moves all tensors in the Results object to the specified device and dtype.
  344. Args:
  345. *args (Any): Variable length argument list to be passed to torch.Tensor.to().
  346. **kwargs (Any): Arbitrary keyword arguments to be passed to torch.Tensor.to().
  347. Returns:
  348. (Results): A new Results object with all tensors moved to the specified device and dtype.
  349. Examples:
  350. >>> results = model("path/to/image.jpg")
  351. >>> result_cuda = results[0].to("cuda") # Move first result to GPU
  352. >>> result_cpu = results[0].to("cpu") # Move first result to CPU
  353. >>> result_half = results[0].to(dtype=torch.float16) # Convert first result to half precision
  354. """
  355. return self._apply("to", *args, **kwargs)
  356. def new(self):
  357. """
  358. Creates a new Results object with the same image, path, names, and speed attributes.
  359. Returns:
  360. (Results): A new Results object with copied attributes from the original instance.
  361. Examples:
  362. >>> results = model("path/to/image.jpg")
  363. >>> new_result = results[0].new()
  364. """
  365. return Results(orig_img=self.orig_img, path=self.path, names=self.names, speed=self.speed)
  366. def plot(
  367. self,
  368. conf=True,
  369. line_width=None,
  370. font_size=None,
  371. font="Arial.ttf",
  372. pil=False,
  373. img=None,
  374. im_gpu=None,
  375. kpt_radius=5,
  376. kpt_line=True,
  377. labels=True,
  378. boxes=True,
  379. masks=True,
  380. probs=True,
  381. show=False,
  382. save=False,
  383. filename=None,
  384. color_mode="class",
  385. ):
  386. """
  387. Plots detection results on an input RGB image.
  388. Args:
  389. conf (bool): Whether to plot detection confidence scores.
  390. line_width (float | None): Line width of bounding boxes. If None, scaled to image size.
  391. font_size (float | None): Font size for text. If None, scaled to image size.
  392. font (str): Font to use for text.
  393. pil (bool): Whether to return the image as a PIL Image.
  394. img (np.ndarray | None): Image to plot on. If None, uses original image.
  395. im_gpu (torch.Tensor | None): Normalized image on GPU for faster mask plotting.
  396. kpt_radius (int): Radius of drawn keypoints.
  397. kpt_line (bool): Whether to draw lines connecting keypoints.
  398. labels (bool): Whether to plot labels of bounding boxes.
  399. boxes (bool): Whether to plot bounding boxes.
  400. masks (bool): Whether to plot masks.
  401. probs (bool): Whether to plot classification probabilities.
  402. show (bool): Whether to display the annotated image.
  403. save (bool): Whether to save the annotated image.
  404. filename (str | None): Filename to save image if save is True.
  405. color_mode (bool): Specify the color mode, e.g., 'instance' or 'class'. Default to 'class'.
  406. Returns:
  407. (np.ndarray): Annotated image as a numpy array.
  408. Examples:
  409. >>> results = model("image.jpg")
  410. >>> for result in results:
  411. ... im = result.plot()
  412. ... im.show()
  413. """
  414. assert color_mode in {"instance", "class"}, f"Expected color_mode='instance' or 'class', not {color_mode}."
  415. if img is None and isinstance(self.orig_img, torch.Tensor):
  416. img = (self.orig_img[0].detach().permute(1, 2, 0).contiguous() * 255).to(torch.uint8).cpu().numpy()
  417. names = self.names
  418. is_obb = self.obb is not None
  419. pred_boxes, show_boxes = self.obb if is_obb else self.boxes, boxes
  420. pred_masks, show_masks = self.masks, masks
  421. pred_probs, show_probs = self.probs, probs
  422. annotator = Annotator(
  423. deepcopy(self.orig_img if img is None else img),
  424. line_width,
  425. font_size,
  426. font,
  427. pil or (pred_probs is not None and show_probs), # Classify tasks default to pil=True
  428. example=names,
  429. )
  430. # Plot Segment results
  431. if pred_masks and show_masks:
  432. if im_gpu is None:
  433. img = LetterBox(pred_masks.shape[1:])(image=annotator.result())
  434. im_gpu = (
  435. torch.as_tensor(img, dtype=torch.float16, device=pred_masks.data.device)
  436. .permute(2, 0, 1)
  437. .flip(0)
  438. .contiguous()
  439. / 255
  440. )
  441. idx = (
  442. pred_boxes.id
  443. if pred_boxes.id is not None and color_mode == "instance"
  444. else pred_boxes.cls
  445. if pred_boxes and color_mode == "class"
  446. else reversed(range(len(pred_masks)))
  447. )
  448. annotator.masks(pred_masks.data, colors=[colors(x, True) for x in idx], im_gpu=im_gpu)
  449. # Plot Detect results
  450. if pred_boxes is not None and show_boxes:
  451. for i, d in enumerate(reversed(pred_boxes)):
  452. c, d_conf, id = int(d.cls), float(d.conf) if conf else None, None if d.id is None else int(d.id.item())
  453. name = ("" if id is None else f"id:{id} ") + names[c]
  454. label = (f"{name} {d_conf:.2f}" if conf else name) if labels else None
  455. box = d.xyxyxyxy.reshape(-1, 4, 2).squeeze() if is_obb else d.xyxy.squeeze()
  456. annotator.box_label(
  457. box,
  458. label,
  459. color=colors(
  460. c
  461. if color_mode == "class"
  462. else id
  463. if id is not None
  464. else i
  465. if color_mode == "instance"
  466. else None,
  467. True,
  468. ),
  469. rotated=is_obb,
  470. )
  471. # Plot Classify results
  472. if pred_probs is not None and show_probs:
  473. text = ",\n".join(f"{names[j] if names else j} {pred_probs.data[j]:.2f}" for j in pred_probs.top5)
  474. x = round(self.orig_shape[0] * 0.03)
  475. annotator.text([x, x], text, txt_color=(255, 255, 255)) # TODO: allow setting colors
  476. # Plot Pose results
  477. if self.keypoints is not None:
  478. for i, k in enumerate(reversed(self.keypoints.data)):
  479. annotator.kpts(
  480. k,
  481. self.orig_shape,
  482. radius=kpt_radius,
  483. kpt_line=kpt_line,
  484. kpt_color=colors(i, True) if color_mode == "instance" else None,
  485. )
  486. # Show results
  487. if show:
  488. annotator.show(self.path)
  489. # Save results
  490. if save:
  491. annotator.save(filename)
  492. return annotator.result()
  493. def show(self, *args, **kwargs):
  494. """
  495. Display the image with annotated inference results.
  496. This method plots the detection results on the original image and displays it. It's a convenient way to
  497. visualize the model's predictions directly.
  498. Args:
  499. *args (Any): Variable length argument list to be passed to the `plot()` method.
  500. **kwargs (Any): Arbitrary keyword arguments to be passed to the `plot()` method.
  501. Examples:
  502. >>> results = model("path/to/image.jpg")
  503. >>> results[0].show() # Display the first result
  504. >>> for result in results:
  505. ... result.show() # Display all results
  506. """
  507. self.plot(show=True, *args, **kwargs)
  508. def save(self, filename=None, *args, **kwargs):
  509. """
  510. Saves annotated inference results image to file.
  511. This method plots the detection results on the original image and saves the annotated image to a file. It
  512. utilizes the `plot` method to generate the annotated image and then saves it to the specified filename.
  513. Args:
  514. filename (str | Path | None): The filename to save the annotated image. If None, a default filename
  515. is generated based on the original image path.
  516. *args (Any): Variable length argument list to be passed to the `plot` method.
  517. **kwargs (Any): Arbitrary keyword arguments to be passed to the `plot` method.
  518. Examples:
  519. >>> results = model("path/to/image.jpg")
  520. >>> for result in results:
  521. ... result.save("annotated_image.jpg")
  522. >>> # Or with custom plot arguments
  523. >>> for result in results:
  524. ... result.save("annotated_image.jpg", conf=False, line_width=2)
  525. """
  526. if not filename:
  527. filename = f"results_{Path(self.path).name}"
  528. self.plot(save=True, filename=filename, *args, **kwargs)
  529. return filename
  530. def verbose(self):
  531. """
  532. Returns a log string for each task in the results, detailing detection and classification outcomes.
  533. This method generates a human-readable string summarizing the detection and classification results. It includes
  534. the number of detections for each class and the top probabilities for classification tasks.
  535. Returns:
  536. (str): A formatted string containing a summary of the results. For detection tasks, it includes the
  537. number of detections per class. For classification tasks, it includes the top 5 class probabilities.
  538. Examples:
  539. >>> results = model("path/to/image.jpg")
  540. >>> for result in results:
  541. ... print(result.verbose())
  542. 2 persons, 1 car, 3 traffic lights,
  543. dog 0.92, cat 0.78, horse 0.64,
  544. Notes:
  545. - If there are no detections, the method returns "(no detections), " for detection tasks.
  546. - For classification tasks, it returns the top 5 class probabilities and their corresponding class names.
  547. - The returned string is comma-separated and ends with a comma and a space.
  548. """
  549. log_string = ""
  550. probs = self.probs
  551. if len(self) == 0:
  552. return log_string if probs is not None else f"{log_string}(no detections), "
  553. if probs is not None:
  554. log_string += f"{', '.join(f'{self.names[j]} {probs.data[j]:.2f}' for j in probs.top5)}, "
  555. if boxes := self.boxes:
  556. for c in boxes.cls.unique():
  557. n = (boxes.cls == c).sum() # detections per class
  558. log_string += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, "
  559. return log_string
  560. def save_txt(self, txt_file, save_conf=False):
  561. """
  562. Save detection results to a text file.
  563. Args:
  564. txt_file (str | Path): Path to the output text file.
  565. save_conf (bool): Whether to include confidence scores in the output.
  566. Returns:
  567. (str): Path to the saved text file.
  568. Examples:
  569. >>> from ultralytics import YOLO
  570. >>> model = YOLO("yolo11n.pt")
  571. >>> results = model("path/to/image.jpg")
  572. >>> for result in results:
  573. ... result.save_txt("output.txt")
  574. Notes:
  575. - The file will contain one line per detection or classification with the following structure:
  576. - For detections: `class confidence x_center y_center width height`
  577. - For classifications: `confidence class_name`
  578. - For masks and keypoints, the specific formats will vary accordingly.
  579. - The function will create the output directory if it does not exist.
  580. - If save_conf is False, the confidence scores will be excluded from the output.
  581. - Existing contents of the file will not be overwritten; new results will be appended.
  582. """
  583. is_obb = self.obb is not None
  584. boxes = self.obb if is_obb else self.boxes
  585. masks = self.masks
  586. probs = self.probs
  587. kpts = self.keypoints
  588. texts = []
  589. if probs is not None:
  590. # Classify
  591. [texts.append(f"{probs.data[j]:.2f} {self.names[j]}") for j in probs.top5]
  592. elif boxes:
  593. # Detect/segment/pose
  594. for j, d in enumerate(boxes):
  595. c, conf, id = int(d.cls), float(d.conf), None if d.id is None else int(d.id.item())
  596. line = (c, *(d.xyxyxyxyn.view(-1) if is_obb else d.xywhn.view(-1)))
  597. if masks:
  598. seg = masks[j].xyn[0].copy().reshape(-1) # reversed mask.xyn, (n,2) to (n*2)
  599. line = (c, *seg)
  600. if kpts is not None:
  601. kpt = torch.cat((kpts[j].xyn, kpts[j].conf[..., None]), 2) if kpts[j].has_visible else kpts[j].xyn
  602. line += (*kpt.reshape(-1).tolist(),)
  603. line += (conf,) * save_conf + (() if id is None else (id,))
  604. texts.append(("%g " * len(line)).rstrip() % line)
  605. if texts:
  606. Path(txt_file).parent.mkdir(parents=True, exist_ok=True) # make directory
  607. with open(txt_file, "a") as f:
  608. f.writelines(text + "\n" for text in texts)
  609. def save_crop(self, save_dir, file_name=Path("im.jpg")):
  610. """
  611. Saves cropped detection images to specified directory.
  612. This method saves cropped images of detected objects to a specified directory. Each crop is saved in a
  613. subdirectory named after the object's class, with the filename based on the input file_name.
  614. Args:
  615. save_dir (str | Path): Directory path where cropped images will be saved.
  616. file_name (str | Path): Base filename for the saved cropped images. Default is Path("im.jpg").
  617. Notes:
  618. - This method does not support Classify or Oriented Bounding Box (OBB) tasks.
  619. - Crops are saved as 'save_dir/class_name/file_name.jpg'.
  620. - The method will create necessary subdirectories if they don't exist.
  621. - Original image is copied before cropping to avoid modifying the original.
  622. Examples:
  623. >>> results = model("path/to/image.jpg")
  624. >>> for result in results:
  625. ... result.save_crop(save_dir="path/to/crops", file_name="detection")
  626. """
  627. if self.probs is not None:
  628. LOGGER.warning("WARNING ⚠️ Classify task do not support `save_crop`.")
  629. return
  630. if self.obb is not None:
  631. LOGGER.warning("WARNING ⚠️ OBB task do not support `save_crop`.")
  632. return
  633. for d in self.boxes:
  634. save_one_box(
  635. d.xyxy,
  636. self.orig_img.copy(),
  637. file=Path(save_dir) / self.names[int(d.cls)] / Path(file_name).with_suffix(".jpg"),
  638. BGR=True,
  639. )
  640. def summary(self, normalize=False, decimals=5):
  641. """
  642. Converts inference results to a summarized dictionary with optional normalization for box coordinates.
  643. This method creates a list of detection dictionaries, each containing information about a single
  644. detection or classification result. For classification tasks, it returns the top class and its
  645. confidence. For detection tasks, it includes class information, bounding box coordinates, and
  646. optionally mask segments and keypoints.
  647. Args:
  648. normalize (bool): Whether to normalize bounding box coordinates by image dimensions. Defaults to False.
  649. decimals (int): Number of decimal places to round the output values to. Defaults to 5.
  650. Returns:
  651. (List[Dict]): A list of dictionaries, each containing summarized information for a single
  652. detection or classification result. The structure of each dictionary varies based on the
  653. task type (classification or detection) and available information (boxes, masks, keypoints).
  654. Examples:
  655. >>> results = model("image.jpg")
  656. >>> summary = results[0].summary()
  657. >>> print(summary)
  658. """
  659. # Create list of detection dictionaries
  660. results = []
  661. if self.probs is not None:
  662. class_id = self.probs.top1
  663. results.append(
  664. {
  665. "name": self.names[class_id],
  666. "class": class_id,
  667. "confidence": round(self.probs.top1conf.item(), decimals),
  668. }
  669. )
  670. return results
  671. is_obb = self.obb is not None
  672. data = self.obb if is_obb else self.boxes
  673. h, w = self.orig_shape if normalize else (1, 1)
  674. for i, row in enumerate(data): # xyxy, track_id if tracking, conf, class_id
  675. class_id, conf = int(row.cls), round(row.conf.item(), decimals)
  676. box = (row.xyxyxyxy if is_obb else row.xyxy).squeeze().reshape(-1, 2).tolist()
  677. xy = {}
  678. for j, b in enumerate(box):
  679. xy[f"x{j + 1}"] = round(b[0] / w, decimals)
  680. xy[f"y{j + 1}"] = round(b[1] / h, decimals)
  681. result = {"name": self.names[class_id], "class": class_id, "confidence": conf, "box": xy}
  682. if data.is_track:
  683. result["track_id"] = int(row.id.item()) # track ID
  684. if self.masks:
  685. result["segments"] = {
  686. "x": (self.masks.xy[i][:, 0] / w).round(decimals).tolist(),
  687. "y": (self.masks.xy[i][:, 1] / h).round(decimals).tolist(),
  688. }
  689. if self.keypoints is not None:
  690. x, y, visible = self.keypoints[i].data[0].cpu().unbind(dim=1) # torch Tensor
  691. result["keypoints"] = {
  692. "x": (x / w).numpy().round(decimals).tolist(), # decimals named argument required
  693. "y": (y / h).numpy().round(decimals).tolist(),
  694. "visible": visible.numpy().round(decimals).tolist(),
  695. }
  696. results.append(result)
  697. return results
  698. def to_df(self, normalize=False, decimals=5):
  699. """
  700. Converts detection results to a Pandas Dataframe.
  701. This method converts the detection results into Pandas Dataframe format. It includes information
  702. about detected objects such as bounding boxes, class names, confidence scores, and optionally
  703. segmentation masks and keypoints.
  704. Args:
  705. normalize (bool): Whether to normalize the bounding box coordinates by the image dimensions.
  706. If True, coordinates will be returned as float values between 0 and 1. Defaults to False.
  707. decimals (int): Number of decimal places to round the output values to. Defaults to 5.
  708. Returns:
  709. (DataFrame): A Pandas Dataframe containing all the information in results in an organized way.
  710. Examples:
  711. >>> results = model("path/to/image.jpg")
  712. >>> df_result = results[0].to_df()
  713. >>> print(df_result)
  714. """
  715. import pandas as pd # scope for faster 'import ultralytics'
  716. return pd.DataFrame(self.summary(normalize=normalize, decimals=decimals))
  717. def to_csv(self, normalize=False, decimals=5, *args, **kwargs):
  718. """
  719. Converts detection results to a CSV format.
  720. This method serializes the detection results into a CSV format. It includes information
  721. about detected objects such as bounding boxes, class names, confidence scores, and optionally
  722. segmentation masks and keypoints.
  723. Args:
  724. normalize (bool): Whether to normalize the bounding box coordinates by the image dimensions.
  725. If True, coordinates will be returned as float values between 0 and 1. Defaults to False.
  726. decimals (int): Number of decimal places to round the output values to. Defaults to 5.
  727. *args (Any): Variable length argument list to be passed to pandas.DataFrame.to_csv().
  728. **kwargs (Any): Arbitrary keyword arguments to be passed to pandas.DataFrame.to_csv().
  729. Returns:
  730. (str): CSV containing all the information in results in an organized way.
  731. Examples:
  732. >>> results = model("path/to/image.jpg")
  733. >>> csv_result = results[0].to_csv()
  734. >>> print(csv_result)
  735. """
  736. return self.to_df(normalize=normalize, decimals=decimals).to_csv(*args, **kwargs)
  737. def to_xml(self, normalize=False, decimals=5, *args, **kwargs):
  738. """
  739. Converts detection results to XML format.
  740. This method serializes the detection results into an XML format. It includes information
  741. about detected objects such as bounding boxes, class names, confidence scores, and optionally
  742. segmentation masks and keypoints.
  743. Args:
  744. normalize (bool): Whether to normalize the bounding box coordinates by the image dimensions.
  745. If True, coordinates will be returned as float values between 0 and 1. Defaults to False.
  746. decimals (int): Number of decimal places to round the output values to. Defaults to 5.
  747. *args (Any): Variable length argument list to be passed to pandas.DataFrame.to_xml().
  748. **kwargs (Any): Arbitrary keyword arguments to be passed to pandas.DataFrame.to_xml().
  749. Returns:
  750. (str): An XML string containing all the information in results in an organized way.
  751. Examples:
  752. >>> results = model("path/to/image.jpg")
  753. >>> xml_result = results[0].to_xml()
  754. >>> print(xml_result)
  755. """
  756. check_requirements("lxml")
  757. df = self.to_df(normalize=normalize, decimals=decimals)
  758. return '<?xml version="1.0" encoding="utf-8"?>\n<root></root>' if df.empty else df.to_xml(*args, **kwargs)
  759. def tojson(self, normalize=False, decimals=5):
  760. """Deprecated version of to_json()."""
  761. LOGGER.warning("WARNING ⚠️ 'result.tojson()' is deprecated, replace with 'result.to_json()'.")
  762. return self.to_json(normalize, decimals)
  763. def to_json(self, normalize=False, decimals=5):
  764. """
  765. Converts detection results to JSON format.
  766. This method serializes the detection results into a JSON-compatible format. It includes information
  767. about detected objects such as bounding boxes, class names, confidence scores, and optionally
  768. segmentation masks and keypoints.
  769. Args:
  770. normalize (bool): Whether to normalize the bounding box coordinates by the image dimensions.
  771. If True, coordinates will be returned as float values between 0 and 1. Defaults to False.
  772. decimals (int): Number of decimal places to round the output values to. Defaults to 5.
  773. Returns:
  774. (str): A JSON string containing the serialized detection results.
  775. Examples:
  776. >>> results = model("path/to/image.jpg")
  777. >>> json_result = results[0].to_json()
  778. >>> print(json_result)
  779. Notes:
  780. - For classification tasks, the JSON will contain class probabilities instead of bounding boxes.
  781. - For object detection tasks, the JSON will include bounding box coordinates, class names, and
  782. confidence scores.
  783. - If available, segmentation masks and keypoints will also be included in the JSON output.
  784. - The method uses the `summary` method internally to generate the data structure before
  785. converting it to JSON.
  786. """
  787. import json
  788. return json.dumps(self.summary(normalize=normalize, decimals=decimals), indent=2)
  789. class Boxes(BaseTensor):
  790. """
  791. A class for managing and manipulating detection boxes.
  792. This class provides functionality for handling detection boxes, including their coordinates, confidence scores,
  793. class labels, and optional tracking IDs. It supports various box formats and offers methods for easy manipulation
  794. and conversion between different coordinate systems.
  795. Attributes:
  796. data (torch.Tensor | numpy.ndarray): The raw tensor containing detection boxes and associated data.
  797. orig_shape (Tuple[int, int]): The original image dimensions (height, width).
  798. is_track (bool): Indicates whether tracking IDs are included in the box data.
  799. xyxy (torch.Tensor | numpy.ndarray): Boxes in [x1, y1, x2, y2] format.
  800. conf (torch.Tensor | numpy.ndarray): Confidence scores for each box.
  801. cls (torch.Tensor | numpy.ndarray): Class labels for each box.
  802. id (torch.Tensor | numpy.ndarray): Tracking IDs for each box (if available).
  803. xywh (torch.Tensor | numpy.ndarray): Boxes in [x, y, width, height] format.
  804. xyxyn (torch.Tensor | numpy.ndarray): Normalized [x1, y1, x2, y2] boxes relative to orig_shape.
  805. xywhn (torch.Tensor | numpy.ndarray): Normalized [x, y, width, height] boxes relative to orig_shape.
  806. Methods:
  807. cpu(): Returns a copy of the object with all tensors on CPU memory.
  808. numpy(): Returns a copy of the object with all tensors as numpy arrays.
  809. cuda(): Returns a copy of the object with all tensors on GPU memory.
  810. to(*args, **kwargs): Returns a copy of the object with tensors on specified device and dtype.
  811. Examples:
  812. >>> import torch
  813. >>> boxes_data = torch.tensor([[100, 50, 150, 100, 0.9, 0], [200, 150, 300, 250, 0.8, 1]])
  814. >>> orig_shape = (480, 640) # height, width
  815. >>> boxes = Boxes(boxes_data, orig_shape)
  816. >>> print(boxes.xyxy)
  817. >>> print(boxes.conf)
  818. >>> print(boxes.cls)
  819. >>> print(boxes.xywhn)
  820. """
  821. def __init__(self, boxes, orig_shape) -> None:
  822. """
  823. Initialize the Boxes class with detection box data and the original image shape.
  824. This class manages detection boxes, providing easy access and manipulation of box coordinates,
  825. confidence scores, class identifiers, and optional tracking IDs. It supports multiple formats
  826. for box coordinates, including both absolute and normalized forms.
  827. Args:
  828. boxes (torch.Tensor | np.ndarray): A tensor or numpy array with detection boxes of shape
  829. (num_boxes, 6) or (num_boxes, 7). Columns should contain
  830. [x1, y1, x2, y2, confidence, class, (optional) track_id].
  831. orig_shape (Tuple[int, int]): The original image shape as (height, width). Used for normalization.
  832. Attributes:
  833. data (torch.Tensor): The raw tensor containing detection boxes and their associated data.
  834. orig_shape (Tuple[int, int]): The original image size, used for normalization.
  835. is_track (bool): Indicates whether tracking IDs are included in the box data.
  836. Examples:
  837. >>> import torch
  838. >>> boxes = torch.tensor([[100, 50, 150, 100, 0.9, 0]])
  839. >>> orig_shape = (480, 640)
  840. >>> detection_boxes = Boxes(boxes, orig_shape)
  841. >>> print(detection_boxes.xyxy)
  842. tensor([[100., 50., 150., 100.]])
  843. """
  844. if boxes.ndim == 1:
  845. boxes = boxes[None, :]
  846. n = boxes.shape[-1]
  847. assert n in {6, 7}, f"expected 6 or 7 values but got {n}" # xyxy, track_id, conf, cls
  848. super().__init__(boxes, orig_shape)
  849. self.is_track = n == 7
  850. self.orig_shape = orig_shape
  851. @property
  852. def xyxy(self):
  853. """
  854. Returns bounding boxes in [x1, y1, x2, y2] format.
  855. Returns:
  856. (torch.Tensor | numpy.ndarray): A tensor or numpy array of shape (n, 4) containing bounding box
  857. coordinates in [x1, y1, x2, y2] format, where n is the number of boxes.
  858. Examples:
  859. >>> results = model("image.jpg")
  860. >>> boxes = results[0].boxes
  861. >>> xyxy = boxes.xyxy
  862. >>> print(xyxy)
  863. """
  864. return self.data[:, :4]
  865. @property
  866. def conf(self):
  867. """
  868. Returns the confidence scores for each detection box.
  869. Returns:
  870. (torch.Tensor | numpy.ndarray): A 1D tensor or array containing confidence scores for each detection,
  871. with shape (N,) where N is the number of detections.
  872. Examples:
  873. >>> boxes = Boxes(torch.tensor([[10, 20, 30, 40, 0.9, 0]]), orig_shape=(100, 100))
  874. >>> conf_scores = boxes.conf
  875. >>> print(conf_scores)
  876. tensor([0.9000])
  877. """
  878. return self.data[:, -2]
  879. @property
  880. def cls(self):
  881. """
  882. Returns the class ID tensor representing category predictions for each bounding box.
  883. Returns:
  884. (torch.Tensor | numpy.ndarray): A tensor or numpy array containing the class IDs for each detection box.
  885. The shape is (N,), where N is the number of boxes.
  886. Examples:
  887. >>> results = model("image.jpg")
  888. >>> boxes = results[0].boxes
  889. >>> class_ids = boxes.cls
  890. >>> print(class_ids) # tensor([0., 2., 1.])
  891. """
  892. return self.data[:, -1]
  893. @property
  894. def id(self):
  895. """
  896. Returns the tracking IDs for each detection box if available.
  897. Returns:
  898. (torch.Tensor | None): A tensor containing tracking IDs for each box if tracking is enabled,
  899. otherwise None. Shape is (N,) where N is the number of boxes.
  900. Examples:
  901. >>> results = model.track("path/to/video.mp4")
  902. >>> for result in results:
  903. ... boxes = result.boxes
  904. ... if boxes.is_track:
  905. ... track_ids = boxes.id
  906. ... print(f"Tracking IDs: {track_ids}")
  907. ... else:
  908. ... print("Tracking is not enabled for these boxes.")
  909. Notes:
  910. - This property is only available when tracking is enabled (i.e., when `is_track` is True).
  911. - The tracking IDs are typically used to associate detections across multiple frames in video analysis.
  912. """
  913. return self.data[:, -3] if self.is_track else None
  914. @property
  915. @lru_cache(maxsize=2) # maxsize 1 should suffice
  916. def xywh(self):
  917. """
  918. Convert bounding boxes from [x1, y1, x2, y2] format to [x, y, width, height] format.
  919. Returns:
  920. (torch.Tensor | numpy.ndarray): Boxes in [x_center, y_center, width, height] format, where x_center, y_center are the coordinates of
  921. the center point of the bounding box, width, height are the dimensions of the bounding box and the
  922. shape of the returned tensor is (N, 4), where N is the number of boxes.
  923. Examples:
  924. >>> boxes = Boxes(torch.tensor([[100, 50, 150, 100], [200, 150, 300, 250]]), orig_shape=(480, 640))
  925. >>> xywh = boxes.xywh
  926. >>> print(xywh)
  927. tensor([[100.0000, 50.0000, 50.0000, 50.0000],
  928. [200.0000, 150.0000, 100.0000, 100.0000]])
  929. """
  930. return ops.xyxy2xywh(self.xyxy)
  931. @property
  932. @lru_cache(maxsize=2)
  933. def xyxyn(self):
  934. """
  935. Returns normalized bounding box coordinates relative to the original image size.
  936. This property calculates and returns the bounding box coordinates in [x1, y1, x2, y2] format,
  937. normalized to the range [0, 1] based on the original image dimensions.
  938. Returns:
  939. (torch.Tensor | numpy.ndarray): Normalized bounding box coordinates with shape (N, 4), where N is
  940. the number of boxes. Each row contains [x1, y1, x2, y2] values normalized to [0, 1].
  941. Examples:
  942. >>> boxes = Boxes(torch.tensor([[100, 50, 300, 400, 0.9, 0]]), orig_shape=(480, 640))
  943. >>> normalized = boxes.xyxyn
  944. >>> print(normalized)
  945. tensor([[0.1562, 0.1042, 0.4688, 0.8333]])
  946. """
  947. xyxy = self.xyxy.clone() if isinstance(self.xyxy, torch.Tensor) else np.copy(self.xyxy)
  948. xyxy[..., [0, 2]] /= self.orig_shape[1]
  949. xyxy[..., [1, 3]] /= self.orig_shape[0]
  950. return xyxy
  951. @property
  952. @lru_cache(maxsize=2)
  953. def xywhn(self):
  954. """
  955. Returns normalized bounding boxes in [x, y, width, height] format.
  956. This property calculates and returns the normalized bounding box coordinates in the format
  957. [x_center, y_center, width, height], where all values are relative to the original image dimensions.
  958. Returns:
  959. (torch.Tensor | numpy.ndarray): Normalized bounding boxes with shape (N, 4), where N is the
  960. number of boxes. Each row contains [x_center, y_center, width, height] values normalized
  961. to [0, 1] based on the original image dimensions.
  962. Examples:
  963. >>> boxes = Boxes(torch.tensor([[100, 50, 150, 100, 0.9, 0]]), orig_shape=(480, 640))
  964. >>> normalized = boxes.xywhn
  965. >>> print(normalized)
  966. tensor([[0.1953, 0.1562, 0.0781, 0.1042]])
  967. """
  968. xywh = ops.xyxy2xywh(self.xyxy)
  969. xywh[..., [0, 2]] /= self.orig_shape[1]
  970. xywh[..., [1, 3]] /= self.orig_shape[0]
  971. return xywh
  972. class Masks(BaseTensor):
  973. """
  974. A class for storing and manipulating detection masks.
  975. This class extends BaseTensor and provides functionality for handling segmentation masks,
  976. including methods for converting between pixel and normalized coordinates.
  977. Attributes:
  978. data (torch.Tensor | numpy.ndarray): The raw tensor or array containing mask data.
  979. orig_shape (tuple): Original image shape in (height, width) format.
  980. xy (List[numpy.ndarray]): A list of segments in pixel coordinates.
  981. xyn (List[numpy.ndarray]): A list of normalized segments.
  982. Methods:
  983. cpu(): Returns a copy of the Masks object with the mask tensor on CPU memory.
  984. numpy(): Returns a copy of the Masks object with the mask tensor as a numpy array.
  985. cuda(): Returns a copy of the Masks object with the mask tensor on GPU memory.
  986. to(*args, **kwargs): Returns a copy of the Masks object with the mask tensor on specified device and dtype.
  987. Examples:
  988. >>> masks_data = torch.rand(1, 160, 160)
  989. >>> orig_shape = (720, 1280)
  990. >>> masks = Masks(masks_data, orig_shape)
  991. >>> pixel_coords = masks.xy
  992. >>> normalized_coords = masks.xyn
  993. """
  994. def __init__(self, masks, orig_shape) -> None:
  995. """
  996. Initialize the Masks class with detection mask data and the original image shape.
  997. Args:
  998. masks (torch.Tensor | np.ndarray): Detection masks with shape (num_masks, height, width).
  999. orig_shape (tuple): The original image shape as (height, width). Used for normalization.
  1000. Examples:
  1001. >>> import torch
  1002. >>> from ultralytics.engine.results import Masks
  1003. >>> masks = torch.rand(10, 160, 160) # 10 masks of 160x160 resolution
  1004. >>> orig_shape = (720, 1280) # Original image shape
  1005. >>> mask_obj = Masks(masks, orig_shape)
  1006. """
  1007. if masks.ndim == 2:
  1008. masks = masks[None, :]
  1009. super().__init__(masks, orig_shape)
  1010. @property
  1011. @lru_cache(maxsize=1)
  1012. def xyn(self):
  1013. """
  1014. Returns normalized xy-coordinates of the segmentation masks.
  1015. This property calculates and caches the normalized xy-coordinates of the segmentation masks. The coordinates
  1016. are normalized relative to the original image shape.
  1017. Returns:
  1018. (List[numpy.ndarray]): A list of numpy arrays, where each array contains the normalized xy-coordinates
  1019. of a single segmentation mask. Each array has shape (N, 2), where N is the number of points in the
  1020. mask contour.
  1021. Examples:
  1022. >>> results = model("image.jpg")
  1023. >>> masks = results[0].masks
  1024. >>> normalized_coords = masks.xyn
  1025. >>> print(normalized_coords[0]) # Normalized coordinates of the first mask
  1026. """
  1027. return [
  1028. ops.scale_coords(self.data.shape[1:], x, self.orig_shape, normalize=True)
  1029. for x in ops.masks2segments(self.data)
  1030. ]
  1031. @property
  1032. @lru_cache(maxsize=1)
  1033. def xy(self):
  1034. """
  1035. Returns the [x, y] pixel coordinates for each segment in the mask tensor.
  1036. This property calculates and returns a list of pixel coordinates for each segmentation mask in the
  1037. Masks object. The coordinates are scaled to match the original image dimensions.
  1038. Returns:
  1039. (List[numpy.ndarray]): A list of numpy arrays, where each array contains the [x, y] pixel
  1040. coordinates for a single segmentation mask. Each array has shape (N, 2), where N is the
  1041. number of points in the segment.
  1042. Examples:
  1043. >>> results = model("image.jpg")
  1044. >>> masks = results[0].masks
  1045. >>> xy_coords = masks.xy
  1046. >>> print(len(xy_coords)) # Number of masks
  1047. >>> print(xy_coords[0].shape) # Shape of first mask's coordinates
  1048. """
  1049. return [
  1050. ops.scale_coords(self.data.shape[1:], x, self.orig_shape, normalize=False)
  1051. for x in ops.masks2segments(self.data)
  1052. ]
  1053. class Keypoints(BaseTensor):
  1054. """
  1055. A class for storing and manipulating detection keypoints.
  1056. This class encapsulates functionality for handling keypoint data, including coordinate manipulation,
  1057. normalization, and confidence values.
  1058. Attributes:
  1059. data (torch.Tensor): The raw tensor containing keypoint data.
  1060. orig_shape (Tuple[int, int]): The original image dimensions (height, width).
  1061. has_visible (bool): Indicates whether visibility information is available for keypoints.
  1062. xy (torch.Tensor): Keypoint coordinates in [x, y] format.
  1063. xyn (torch.Tensor): Normalized keypoint coordinates in [x, y] format, relative to orig_shape.
  1064. conf (torch.Tensor): Confidence values for each keypoint, if available.
  1065. Methods:
  1066. cpu(): Returns a copy of the keypoints tensor on CPU memory.
  1067. numpy(): Returns a copy of the keypoints tensor as a numpy array.
  1068. cuda(): Returns a copy of the keypoints tensor on GPU memory.
  1069. to(*args, **kwargs): Returns a copy of the keypoints tensor with specified device and dtype.
  1070. Examples:
  1071. >>> import torch
  1072. >>> from ultralytics.engine.results import Keypoints
  1073. >>> keypoints_data = torch.rand(1, 17, 3) # 1 detection, 17 keypoints, (x, y, conf)
  1074. >>> orig_shape = (480, 640) # Original image shape (height, width)
  1075. >>> keypoints = Keypoints(keypoints_data, orig_shape)
  1076. >>> print(keypoints.xy.shape) # Access xy coordinates
  1077. >>> print(keypoints.conf) # Access confidence values
  1078. >>> keypoints_cpu = keypoints.cpu() # Move keypoints to CPU
  1079. """
  1080. @smart_inference_mode() # avoid keypoints < conf in-place error
  1081. def __init__(self, keypoints, orig_shape) -> None:
  1082. """
  1083. Initializes the Keypoints object with detection keypoints and original image dimensions.
  1084. This method processes the input keypoints tensor, handling both 2D and 3D formats. For 3D tensors
  1085. (x, y, confidence), it masks out low-confidence keypoints by setting their coordinates to zero.
  1086. Args:
  1087. keypoints (torch.Tensor): A tensor containing keypoint data. Shape can be either:
  1088. - (num_objects, num_keypoints, 2) for x, y coordinates only
  1089. - (num_objects, num_keypoints, 3) for x, y coordinates and confidence scores
  1090. orig_shape (Tuple[int, int]): The original image dimensions (height, width).
  1091. Examples:
  1092. >>> kpts = torch.rand(1, 17, 3) # 1 object, 17 keypoints (COCO format), x,y,conf
  1093. >>> orig_shape = (720, 1280) # Original image height, width
  1094. >>> keypoints = Keypoints(kpts, orig_shape)
  1095. """
  1096. if keypoints.ndim == 2:
  1097. keypoints = keypoints[None, :]
  1098. if keypoints.shape[2] == 3: # x, y, conf
  1099. mask = keypoints[..., 2] < 0.5 # points with conf < 0.5 (not visible)
  1100. keypoints[..., :2][mask] = 0
  1101. super().__init__(keypoints, orig_shape)
  1102. self.has_visible = self.data.shape[-1] == 3
  1103. @property
  1104. @lru_cache(maxsize=1)
  1105. def xy(self):
  1106. """
  1107. Returns x, y coordinates of keypoints.
  1108. Returns:
  1109. (torch.Tensor): A tensor containing the x, y coordinates of keypoints with shape (N, K, 2), where N is
  1110. the number of detections and K is the number of keypoints per detection.
  1111. Examples:
  1112. >>> results = model("image.jpg")
  1113. >>> keypoints = results[0].keypoints
  1114. >>> xy = keypoints.xy
  1115. >>> print(xy.shape) # (N, K, 2)
  1116. >>> print(xy[0]) # x, y coordinates of keypoints for first detection
  1117. Notes:
  1118. - The returned coordinates are in pixel units relative to the original image dimensions.
  1119. - If keypoints were initialized with confidence values, only keypoints with confidence >= 0.5 are returned.
  1120. - This property uses LRU caching to improve performance on repeated access.
  1121. """
  1122. return self.data[..., :2]
  1123. @property
  1124. @lru_cache(maxsize=1)
  1125. def xyn(self):
  1126. """
  1127. Returns normalized coordinates (x, y) of keypoints relative to the original image size.
  1128. Returns:
  1129. (torch.Tensor | numpy.ndarray): A tensor or array of shape (N, K, 2) containing normalized keypoint
  1130. coordinates, where N is the number of instances, K is the number of keypoints, and the last
  1131. dimension contains [x, y] values in the range [0, 1].
  1132. Examples:
  1133. >>> keypoints = Keypoints(torch.rand(1, 17, 2), orig_shape=(480, 640))
  1134. >>> normalized_kpts = keypoints.xyn
  1135. >>> print(normalized_kpts.shape)
  1136. torch.Size([1, 17, 2])
  1137. """
  1138. xy = self.xy.clone() if isinstance(self.xy, torch.Tensor) else np.copy(self.xy)
  1139. xy[..., 0] /= self.orig_shape[1]
  1140. xy[..., 1] /= self.orig_shape[0]
  1141. return xy
  1142. @property
  1143. @lru_cache(maxsize=1)
  1144. def conf(self):
  1145. """
  1146. Returns confidence values for each keypoint.
  1147. Returns:
  1148. (torch.Tensor | None): A tensor containing confidence scores for each keypoint if available,
  1149. otherwise None. Shape is (num_detections, num_keypoints) for batched data or (num_keypoints,)
  1150. for single detection.
  1151. Examples:
  1152. >>> keypoints = Keypoints(torch.rand(1, 17, 3), orig_shape=(640, 640)) # 1 detection, 17 keypoints
  1153. >>> conf = keypoints.conf
  1154. >>> print(conf.shape) # torch.Size([1, 17])
  1155. """
  1156. return self.data[..., 2] if self.has_visible else None
  1157. class Probs(BaseTensor):
  1158. """
  1159. A class for storing and manipulating classification probabilities.
  1160. This class extends BaseTensor and provides methods for accessing and manipulating
  1161. classification probabilities, including top-1 and top-5 predictions.
  1162. Attributes:
  1163. data (torch.Tensor | numpy.ndarray): The raw tensor or array containing classification probabilities.
  1164. orig_shape (tuple | None): The original image shape as (height, width). Not used in this class.
  1165. top1 (int): Index of the class with the highest probability.
  1166. top5 (List[int]): Indices of the top 5 classes by probability.
  1167. top1conf (torch.Tensor | numpy.ndarray): Confidence score of the top 1 class.
  1168. top5conf (torch.Tensor | numpy.ndarray): Confidence scores of the top 5 classes.
  1169. Methods:
  1170. cpu(): Returns a copy of the probabilities tensor on CPU memory.
  1171. numpy(): Returns a copy of the probabilities tensor as a numpy array.
  1172. cuda(): Returns a copy of the probabilities tensor on GPU memory.
  1173. to(*args, **kwargs): Returns a copy of the probabilities tensor with specified device and dtype.
  1174. Examples:
  1175. >>> probs = torch.tensor([0.1, 0.3, 0.6])
  1176. >>> p = Probs(probs)
  1177. >>> print(p.top1)
  1178. 2
  1179. >>> print(p.top5)
  1180. [2, 1, 0]
  1181. >>> print(p.top1conf)
  1182. tensor(0.6000)
  1183. >>> print(p.top5conf)
  1184. tensor([0.6000, 0.3000, 0.1000])
  1185. """
  1186. def __init__(self, probs, orig_shape=None) -> None:
  1187. """
  1188. Initialize the Probs class with classification probabilities.
  1189. This class stores and manages classification probabilities, providing easy access to top predictions and their
  1190. confidences.
  1191. Args:
  1192. probs (torch.Tensor | np.ndarray): A 1D tensor or array of classification probabilities.
  1193. orig_shape (tuple | None): The original image shape as (height, width). Not used in this class but kept for
  1194. consistency with other result classes.
  1195. Attributes:
  1196. data (torch.Tensor | np.ndarray): The raw tensor or array containing classification probabilities.
  1197. top1 (int): Index of the top 1 class.
  1198. top5 (List[int]): Indices of the top 5 classes.
  1199. top1conf (torch.Tensor | np.ndarray): Confidence of the top 1 class.
  1200. top5conf (torch.Tensor | np.ndarray): Confidences of the top 5 classes.
  1201. Examples:
  1202. >>> import torch
  1203. >>> probs = torch.tensor([0.1, 0.3, 0.2, 0.4])
  1204. >>> p = Probs(probs)
  1205. >>> print(p.top1)
  1206. 3
  1207. >>> print(p.top1conf)
  1208. tensor(0.4000)
  1209. >>> print(p.top5)
  1210. [3, 1, 2, 0]
  1211. """
  1212. super().__init__(probs, orig_shape)
  1213. @property
  1214. @lru_cache(maxsize=1)
  1215. def top1(self):
  1216. """
  1217. Returns the index of the class with the highest probability.
  1218. Returns:
  1219. (int): Index of the class with the highest probability.
  1220. Examples:
  1221. >>> probs = Probs(torch.tensor([0.1, 0.3, 0.6]))
  1222. >>> probs.top1
  1223. 2
  1224. """
  1225. return int(self.data.argmax())
  1226. @property
  1227. @lru_cache(maxsize=1)
  1228. def top5(self):
  1229. """
  1230. Returns the indices of the top 5 class probabilities.
  1231. Returns:
  1232. (List[int]): A list containing the indices of the top 5 class probabilities, sorted in descending order.
  1233. Examples:
  1234. >>> probs = Probs(torch.tensor([0.1, 0.2, 0.3, 0.4, 0.5]))
  1235. >>> print(probs.top5)
  1236. [4, 3, 2, 1, 0]
  1237. """
  1238. return (-self.data).argsort(0)[:5].tolist() # this way works with both torch and numpy.
  1239. @property
  1240. @lru_cache(maxsize=1)
  1241. def top1conf(self):
  1242. """
  1243. Returns the confidence score of the highest probability class.
  1244. This property retrieves the confidence score (probability) of the class with the highest predicted probability
  1245. from the classification results.
  1246. Returns:
  1247. (torch.Tensor | numpy.ndarray): A tensor containing the confidence score of the top 1 class.
  1248. Examples:
  1249. >>> results = model("image.jpg") # classify an image
  1250. >>> probs = results[0].probs # get classification probabilities
  1251. >>> top1_confidence = probs.top1conf # get confidence of top 1 class
  1252. >>> print(f"Top 1 class confidence: {top1_confidence.item():.4f}")
  1253. """
  1254. return self.data[self.top1]
  1255. @property
  1256. @lru_cache(maxsize=1)
  1257. def top5conf(self):
  1258. """
  1259. Returns confidence scores for the top 5 classification predictions.
  1260. This property retrieves the confidence scores corresponding to the top 5 class probabilities
  1261. predicted by the model. It provides a quick way to access the most likely class predictions
  1262. along with their associated confidence levels.
  1263. Returns:
  1264. (torch.Tensor | numpy.ndarray): A tensor or array containing the confidence scores for the
  1265. top 5 predicted classes, sorted in descending order of probability.
  1266. Examples:
  1267. >>> results = model("image.jpg")
  1268. >>> probs = results[0].probs
  1269. >>> top5_conf = probs.top5conf
  1270. >>> print(top5_conf) # Prints confidence scores for top 5 classes
  1271. """
  1272. return self.data[self.top5]
  1273. class OBB(BaseTensor):
  1274. """
  1275. A class for storing and manipulating Oriented Bounding Boxes (OBB).
  1276. This class provides functionality to handle oriented bounding boxes, including conversion between
  1277. different formats, normalization, and access to various properties of the boxes.
  1278. Attributes:
  1279. data (torch.Tensor): The raw OBB tensor containing box coordinates and associated data.
  1280. orig_shape (tuple): Original image size as (height, width).
  1281. is_track (bool): Indicates whether tracking IDs are included in the box data.
  1282. xywhr (torch.Tensor | numpy.ndarray): Boxes in [x_center, y_center, width, height, rotation] format.
  1283. conf (torch.Tensor | numpy.ndarray): Confidence scores for each box.
  1284. cls (torch.Tensor | numpy.ndarray): Class labels for each box.
  1285. id (torch.Tensor | numpy.ndarray): Tracking IDs for each box, if available.
  1286. xyxyxyxy (torch.Tensor | numpy.ndarray): Boxes in 8-point [x1, y1, x2, y2, x3, y3, x4, y4] format.
  1287. xyxyxyxyn (torch.Tensor | numpy.ndarray): Normalized 8-point coordinates relative to orig_shape.
  1288. xyxy (torch.Tensor | numpy.ndarray): Axis-aligned bounding boxes in [x1, y1, x2, y2] format.
  1289. Methods:
  1290. cpu(): Returns a copy of the OBB object with all tensors on CPU memory.
  1291. numpy(): Returns a copy of the OBB object with all tensors as numpy arrays.
  1292. cuda(): Returns a copy of the OBB object with all tensors on GPU memory.
  1293. to(*args, **kwargs): Returns a copy of the OBB object with tensors on specified device and dtype.
  1294. Examples:
  1295. >>> boxes = torch.tensor([[100, 50, 150, 100, 30, 0.9, 0]]) # xywhr, conf, cls
  1296. >>> obb = OBB(boxes, orig_shape=(480, 640))
  1297. >>> print(obb.xyxyxyxy)
  1298. >>> print(obb.conf)
  1299. >>> print(obb.cls)
  1300. """
  1301. def __init__(self, boxes, orig_shape) -> None:
  1302. """
  1303. Initialize an OBB (Oriented Bounding Box) instance with oriented bounding box data and original image shape.
  1304. This class stores and manipulates Oriented Bounding Boxes (OBB) for object detection tasks. It provides
  1305. various properties and methods to access and transform the OBB data.
  1306. Args:
  1307. boxes (torch.Tensor | numpy.ndarray): A tensor or numpy array containing the detection boxes,
  1308. with shape (num_boxes, 7) or (num_boxes, 8). The last two columns contain confidence and class values.
  1309. If present, the third last column contains track IDs, and the fifth column contains rotation.
  1310. orig_shape (Tuple[int, int]): Original image size, in the format (height, width).
  1311. Attributes:
  1312. data (torch.Tensor | numpy.ndarray): The raw OBB tensor.
  1313. orig_shape (Tuple[int, int]): The original image shape.
  1314. is_track (bool): Whether the boxes include tracking IDs.
  1315. Raises:
  1316. AssertionError: If the number of values per box is not 7 or 8.
  1317. Examples:
  1318. >>> import torch
  1319. >>> boxes = torch.rand(3, 7) # 3 boxes with 7 values each
  1320. >>> orig_shape = (640, 480)
  1321. >>> obb = OBB(boxes, orig_shape)
  1322. >>> print(obb.xywhr) # Access the boxes in xywhr format
  1323. """
  1324. if boxes.ndim == 1:
  1325. boxes = boxes[None, :]
  1326. n = boxes.shape[-1]
  1327. assert n in {7, 8}, f"expected 7 or 8 values but got {n}" # xywh, rotation, track_id, conf, cls
  1328. super().__init__(boxes, orig_shape)
  1329. self.is_track = n == 8
  1330. self.orig_shape = orig_shape
  1331. @property
  1332. def xywhr(self):
  1333. """
  1334. Returns boxes in [x_center, y_center, width, height, rotation] format.
  1335. Returns:
  1336. (torch.Tensor | numpy.ndarray): A tensor or numpy array containing the oriented bounding boxes with format
  1337. [x_center, y_center, width, height, rotation]. The shape is (N, 5) where N is the number of boxes.
  1338. Examples:
  1339. >>> results = model("image.jpg")
  1340. >>> obb = results[0].obb
  1341. >>> xywhr = obb.xywhr
  1342. >>> print(xywhr.shape)
  1343. torch.Size([3, 5])
  1344. """
  1345. return self.data[:, :5]
  1346. @property
  1347. def conf(self):
  1348. """
  1349. Returns the confidence scores for Oriented Bounding Boxes (OBBs).
  1350. This property retrieves the confidence values associated with each OBB detection. The confidence score
  1351. represents the model's certainty in the detection.
  1352. Returns:
  1353. (torch.Tensor | numpy.ndarray): A tensor or numpy array of shape (N,) containing confidence scores
  1354. for N detections, where each score is in the range [0, 1].
  1355. Examples:
  1356. >>> results = model("image.jpg")
  1357. >>> obb_result = results[0].obb
  1358. >>> confidence_scores = obb_result.conf
  1359. >>> print(confidence_scores)
  1360. """
  1361. return self.data[:, -2]
  1362. @property
  1363. def cls(self):
  1364. """
  1365. Returns the class values of the oriented bounding boxes.
  1366. Returns:
  1367. (torch.Tensor | numpy.ndarray): A tensor or numpy array containing the class values for each oriented
  1368. bounding box. The shape is (N,), where N is the number of boxes.
  1369. Examples:
  1370. >>> results = model("image.jpg")
  1371. >>> result = results[0]
  1372. >>> obb = result.obb
  1373. >>> class_values = obb.cls
  1374. >>> print(class_values)
  1375. """
  1376. return self.data[:, -1]
  1377. @property
  1378. def id(self):
  1379. """
  1380. Returns the tracking IDs of the oriented bounding boxes (if available).
  1381. Returns:
  1382. (torch.Tensor | numpy.ndarray | None): A tensor or numpy array containing the tracking IDs for each
  1383. oriented bounding box. Returns None if tracking IDs are not available.
  1384. Examples:
  1385. >>> results = model("image.jpg", tracker=True) # Run inference with tracking
  1386. >>> for result in results:
  1387. ... if result.obb is not None:
  1388. ... track_ids = result.obb.id
  1389. ... if track_ids is not None:
  1390. ... print(f"Tracking IDs: {track_ids}")
  1391. """
  1392. return self.data[:, -3] if self.is_track else None
  1393. @property
  1394. @lru_cache(maxsize=2)
  1395. def xyxyxyxy(self):
  1396. """
  1397. Converts OBB format to 8-point (xyxyxyxy) coordinate format for rotated bounding boxes.
  1398. Returns:
  1399. (torch.Tensor | numpy.ndarray): Rotated bounding boxes in xyxyxyxy format with shape (N, 4, 2), where N is
  1400. the number of boxes. Each box is represented by 4 points (x, y), starting from the top-left corner and
  1401. moving clockwise.
  1402. Examples:
  1403. >>> obb = OBB(torch.tensor([[100, 100, 50, 30, 0.5, 0.9, 0]]), orig_shape=(640, 640))
  1404. >>> xyxyxyxy = obb.xyxyxyxy
  1405. >>> print(xyxyxyxy.shape)
  1406. torch.Size([1, 4, 2])
  1407. """
  1408. return ops.xywhr2xyxyxyxy(self.xywhr)
  1409. @property
  1410. @lru_cache(maxsize=2)
  1411. def xyxyxyxyn(self):
  1412. """
  1413. Converts rotated bounding boxes to normalized xyxyxyxy format.
  1414. Returns:
  1415. (torch.Tensor | numpy.ndarray): Normalized rotated bounding boxes in xyxyxyxy format with shape (N, 4, 2),
  1416. where N is the number of boxes. Each box is represented by 4 points (x, y), normalized relative to
  1417. the original image dimensions.
  1418. Examples:
  1419. >>> obb = OBB(torch.rand(10, 7), orig_shape=(640, 480)) # 10 random OBBs
  1420. >>> normalized_boxes = obb.xyxyxyxyn
  1421. >>> print(normalized_boxes.shape)
  1422. torch.Size([10, 4, 2])
  1423. """
  1424. xyxyxyxyn = self.xyxyxyxy.clone() if isinstance(self.xyxyxyxy, torch.Tensor) else np.copy(self.xyxyxyxy)
  1425. xyxyxyxyn[..., 0] /= self.orig_shape[1]
  1426. xyxyxyxyn[..., 1] /= self.orig_shape[0]
  1427. return xyxyxyxyn
  1428. @property
  1429. @lru_cache(maxsize=2)
  1430. def xyxy(self):
  1431. """
  1432. Converts oriented bounding boxes (OBB) to axis-aligned bounding boxes in xyxy format.
  1433. This property calculates the minimal enclosing rectangle for each oriented bounding box and returns it in
  1434. xyxy format (x1, y1, x2, y2). This is useful for operations that require axis-aligned bounding boxes, such
  1435. as IoU calculation with non-rotated boxes.
  1436. Returns:
  1437. (torch.Tensor | numpy.ndarray): Axis-aligned bounding boxes in xyxy format with shape (N, 4), where N
  1438. is the number of boxes. Each row contains [x1, y1, x2, y2] coordinates.
  1439. Examples:
  1440. >>> import torch
  1441. >>> from ultralytics import YOLO
  1442. >>> model = YOLO("yolov8n-obb.pt")
  1443. >>> results = model("path/to/image.jpg")
  1444. >>> for result in results:
  1445. ... obb = result.obb
  1446. ... if obb is not None:
  1447. ... xyxy_boxes = obb.xyxy
  1448. ... print(xyxy_boxes.shape) # (N, 4)
  1449. Notes:
  1450. - This method approximates the OBB by its minimal enclosing rectangle.
  1451. - The returned format is compatible with standard object detection metrics and visualization tools.
  1452. - The property uses caching to improve performance for repeated access.
  1453. """
  1454. x = self.xyxyxyxy[..., 0]
  1455. y = self.xyxyxyxy[..., 1]
  1456. return (
  1457. torch.stack([x.amin(1), y.amin(1), x.amax(1), y.amax(1)], -1)
  1458. if isinstance(x, torch.Tensor)
  1459. else np.stack([x.min(1), y.min(1), x.max(1), y.max(1)], -1)
  1460. )