instance.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. from collections import abc
  3. from itertools import repeat
  4. from numbers import Number
  5. from typing import List
  6. import numpy as np
  7. from .ops import ltwh2xywh, ltwh2xyxy, xywh2ltwh, xywh2xyxy, xyxy2ltwh, xyxy2xywh
  8. def _ntuple(n):
  9. """From PyTorch internals."""
  10. def parse(x):
  11. """Parse bounding boxes format between XYWH and LTWH."""
  12. return x if isinstance(x, abc.Iterable) else tuple(repeat(x, n))
  13. return parse
  14. to_2tuple = _ntuple(2)
  15. to_4tuple = _ntuple(4)
  16. # `xyxy` means left top and right bottom
  17. # `xywh` means center x, center y and width, height(YOLO format)
  18. # `ltwh` means left top and width, height(COCO format)
  19. _formats = ["xyxy", "xywh", "ltwh"]
  20. __all__ = ("Bboxes",) # tuple or list
  21. class Bboxes:
  22. """
  23. A class for handling bounding boxes.
  24. The class supports various bounding box formats like 'xyxy', 'xywh', and 'ltwh'.
  25. Bounding box data should be provided in numpy arrays.
  26. Attributes:
  27. bboxes (numpy.ndarray): The bounding boxes stored in a 2D numpy array.
  28. format (str): The format of the bounding boxes ('xyxy', 'xywh', or 'ltwh').
  29. Note:
  30. This class does not handle normalization or denormalization of bounding boxes.
  31. """
  32. def __init__(self, bboxes, format="xyxy") -> None:
  33. """Initializes the Bboxes class with bounding box data in a specified format."""
  34. assert format in _formats, f"Invalid bounding box format: {format}, format must be one of {_formats}"
  35. bboxes = bboxes[None, :] if bboxes.ndim == 1 else bboxes
  36. assert bboxes.ndim == 2
  37. assert bboxes.shape[1] == 4
  38. self.bboxes = bboxes
  39. self.format = format
  40. # self.normalized = normalized
  41. def convert(self, format):
  42. """Converts bounding box format from one type to another."""
  43. assert format in _formats, f"Invalid bounding box format: {format}, format must be one of {_formats}"
  44. if self.format == format:
  45. return
  46. elif self.format == "xyxy":
  47. func = xyxy2xywh if format == "xywh" else xyxy2ltwh
  48. elif self.format == "xywh":
  49. func = xywh2xyxy if format == "xyxy" else xywh2ltwh
  50. else:
  51. func = ltwh2xyxy if format == "xyxy" else ltwh2xywh
  52. self.bboxes = func(self.bboxes)
  53. self.format = format
  54. def areas(self):
  55. """Return box areas."""
  56. return (
  57. (self.bboxes[:, 2] - self.bboxes[:, 0]) * (self.bboxes[:, 3] - self.bboxes[:, 1]) # format xyxy
  58. if self.format == "xyxy"
  59. else self.bboxes[:, 3] * self.bboxes[:, 2] # format xywh or ltwh
  60. )
  61. # def denormalize(self, w, h):
  62. # if not self.normalized:
  63. # return
  64. # assert (self.bboxes <= 1.0).all()
  65. # self.bboxes[:, 0::2] *= w
  66. # self.bboxes[:, 1::2] *= h
  67. # self.normalized = False
  68. #
  69. # def normalize(self, w, h):
  70. # if self.normalized:
  71. # return
  72. # assert (self.bboxes > 1.0).any()
  73. # self.bboxes[:, 0::2] /= w
  74. # self.bboxes[:, 1::2] /= h
  75. # self.normalized = True
  76. def mul(self, scale):
  77. """
  78. Args:
  79. scale (tuple | list | int): the scale for four coords.
  80. """
  81. if isinstance(scale, Number):
  82. scale = to_4tuple(scale)
  83. assert isinstance(scale, (tuple, list))
  84. assert len(scale) == 4
  85. self.bboxes[:, 0] *= scale[0]
  86. self.bboxes[:, 1] *= scale[1]
  87. self.bboxes[:, 2] *= scale[2]
  88. self.bboxes[:, 3] *= scale[3]
  89. def add(self, offset):
  90. """
  91. Args:
  92. offset (tuple | list | int): the offset for four coords.
  93. """
  94. if isinstance(offset, Number):
  95. offset = to_4tuple(offset)
  96. assert isinstance(offset, (tuple, list))
  97. assert len(offset) == 4
  98. self.bboxes[:, 0] += offset[0]
  99. self.bboxes[:, 1] += offset[1]
  100. self.bboxes[:, 2] += offset[2]
  101. self.bboxes[:, 3] += offset[3]
  102. def __len__(self):
  103. """Return the number of boxes."""
  104. return len(self.bboxes)
  105. @classmethod
  106. def concatenate(cls, boxes_list: List["Bboxes"], axis=0) -> "Bboxes":
  107. """
  108. Concatenate a list of Bboxes objects into a single Bboxes object.
  109. Args:
  110. boxes_list (List[Bboxes]): A list of Bboxes objects to concatenate.
  111. axis (int, optional): The axis along which to concatenate the bounding boxes.
  112. Defaults to 0.
  113. Returns:
  114. Bboxes: A new Bboxes object containing the concatenated bounding boxes.
  115. Note:
  116. The input should be a list or tuple of Bboxes objects.
  117. """
  118. assert isinstance(boxes_list, (list, tuple))
  119. if not boxes_list:
  120. return cls(np.empty(0))
  121. assert all(isinstance(box, Bboxes) for box in boxes_list)
  122. if len(boxes_list) == 1:
  123. return boxes_list[0]
  124. return cls(np.concatenate([b.bboxes for b in boxes_list], axis=axis))
  125. def __getitem__(self, index) -> "Bboxes":
  126. """
  127. Retrieve a specific bounding box or a set of bounding boxes using indexing.
  128. Args:
  129. index (int, slice, or np.ndarray): The index, slice, or boolean array to select
  130. the desired bounding boxes.
  131. Returns:
  132. Bboxes: A new Bboxes object containing the selected bounding boxes.
  133. Raises:
  134. AssertionError: If the indexed bounding boxes do not form a 2-dimensional matrix.
  135. Note:
  136. When using boolean indexing, make sure to provide a boolean array with the same
  137. length as the number of bounding boxes.
  138. """
  139. if isinstance(index, int):
  140. return Bboxes(self.bboxes[index].view(1, -1))
  141. b = self.bboxes[index]
  142. assert b.ndim == 2, f"Indexing on Bboxes with {index} failed to return a matrix!"
  143. return Bboxes(b)
  144. class Instances:
  145. """
  146. Container for bounding boxes, segments, and keypoints of detected objects in an image.
  147. Attributes:
  148. _bboxes (Bboxes): Internal object for handling bounding box operations.
  149. keypoints (ndarray): keypoints(x, y, visible) with shape [N, 17, 3]. Default is None.
  150. normalized (bool): Flag indicating whether the bounding box coordinates are normalized.
  151. segments (ndarray): Segments array with shape [N, 1000, 2] after resampling.
  152. Args:
  153. bboxes (ndarray): An array of bounding boxes with shape [N, 4].
  154. segments (list | ndarray, optional): A list or array of object segments. Default is None.
  155. keypoints (ndarray, optional): An array of keypoints with shape [N, 17, 3]. Default is None.
  156. bbox_format (str, optional): The format of bounding boxes ('xywh' or 'xyxy'). Default is 'xywh'.
  157. normalized (bool, optional): Whether the bounding box coordinates are normalized. Default is True.
  158. Examples:
  159. ```python
  160. # Create an Instances object
  161. instances = Instances(
  162. bboxes=np.array([[10, 10, 30, 30], [20, 20, 40, 40]]),
  163. segments=[np.array([[5, 5], [10, 10]]), np.array([[15, 15], [20, 20]])],
  164. keypoints=np.array([[[5, 5, 1], [10, 10, 1]], [[15, 15, 1], [20, 20, 1]]])
  165. )
  166. ```
  167. Note:
  168. The bounding box format is either 'xywh' or 'xyxy', and is determined by the `bbox_format` argument.
  169. This class does not perform input validation, and it assumes the inputs are well-formed.
  170. """
  171. def __init__(self, bboxes, segments=None, keypoints=None, bbox_format="xywh", normalized=True) -> None:
  172. """
  173. Args:
  174. bboxes (ndarray): bboxes with shape [N, 4].
  175. segments (list | ndarray): segments.
  176. keypoints (ndarray): keypoints(x, y, visible) with shape [N, 17, 3].
  177. """
  178. self._bboxes = Bboxes(bboxes=bboxes, format=bbox_format)
  179. self.keypoints = keypoints
  180. self.normalized = normalized
  181. self.segments = segments
  182. def convert_bbox(self, format):
  183. """Convert bounding box format."""
  184. self._bboxes.convert(format=format)
  185. @property
  186. def bbox_areas(self):
  187. """Calculate the area of bounding boxes."""
  188. return self._bboxes.areas()
  189. def scale(self, scale_w, scale_h, bbox_only=False):
  190. """This might be similar with denormalize func but without normalized sign."""
  191. self._bboxes.mul(scale=(scale_w, scale_h, scale_w, scale_h))
  192. if bbox_only:
  193. return
  194. self.segments[..., 0] *= scale_w
  195. self.segments[..., 1] *= scale_h
  196. if self.keypoints is not None:
  197. self.keypoints[..., 0] *= scale_w
  198. self.keypoints[..., 1] *= scale_h
  199. def denormalize(self, w, h):
  200. """Denormalizes boxes, segments, and keypoints from normalized coordinates."""
  201. if not self.normalized:
  202. return
  203. self._bboxes.mul(scale=(w, h, w, h))
  204. self.segments[..., 0] *= w
  205. self.segments[..., 1] *= h
  206. if self.keypoints is not None:
  207. self.keypoints[..., 0] *= w
  208. self.keypoints[..., 1] *= h
  209. self.normalized = False
  210. def normalize(self, w, h):
  211. """Normalize bounding boxes, segments, and keypoints to image dimensions."""
  212. if self.normalized:
  213. return
  214. self._bboxes.mul(scale=(1 / w, 1 / h, 1 / w, 1 / h))
  215. self.segments[..., 0] /= w
  216. self.segments[..., 1] /= h
  217. if self.keypoints is not None:
  218. self.keypoints[..., 0] /= w
  219. self.keypoints[..., 1] /= h
  220. self.normalized = True
  221. def add_padding(self, padw, padh):
  222. """Handle rect and mosaic situation."""
  223. assert not self.normalized, "you should add padding with absolute coordinates."
  224. self._bboxes.add(offset=(padw, padh, padw, padh))
  225. self.segments[..., 0] += padw
  226. self.segments[..., 1] += padh
  227. if self.keypoints is not None:
  228. self.keypoints[..., 0] += padw
  229. self.keypoints[..., 1] += padh
  230. def __getitem__(self, index) -> "Instances":
  231. """
  232. Retrieve a specific instance or a set of instances using indexing.
  233. Args:
  234. index (int, slice, or np.ndarray): The index, slice, or boolean array to select
  235. the desired instances.
  236. Returns:
  237. Instances: A new Instances object containing the selected bounding boxes,
  238. segments, and keypoints if present.
  239. Note:
  240. When using boolean indexing, make sure to provide a boolean array with the same
  241. length as the number of instances.
  242. """
  243. segments = self.segments[index] if len(self.segments) else self.segments
  244. keypoints = self.keypoints[index] if self.keypoints is not None else None
  245. bboxes = self.bboxes[index]
  246. bbox_format = self._bboxes.format
  247. return Instances(
  248. bboxes=bboxes,
  249. segments=segments,
  250. keypoints=keypoints,
  251. bbox_format=bbox_format,
  252. normalized=self.normalized,
  253. )
  254. def flipud(self, h):
  255. """Flips the coordinates of bounding boxes, segments, and keypoints vertically."""
  256. if self._bboxes.format == "xyxy":
  257. y1 = self.bboxes[:, 1].copy()
  258. y2 = self.bboxes[:, 3].copy()
  259. self.bboxes[:, 1] = h - y2
  260. self.bboxes[:, 3] = h - y1
  261. else:
  262. self.bboxes[:, 1] = h - self.bboxes[:, 1]
  263. self.segments[..., 1] = h - self.segments[..., 1]
  264. if self.keypoints is not None:
  265. self.keypoints[..., 1] = h - self.keypoints[..., 1]
  266. def fliplr(self, w):
  267. """Reverses the order of the bounding boxes and segments horizontally."""
  268. if self._bboxes.format == "xyxy":
  269. x1 = self.bboxes[:, 0].copy()
  270. x2 = self.bboxes[:, 2].copy()
  271. self.bboxes[:, 0] = w - x2
  272. self.bboxes[:, 2] = w - x1
  273. else:
  274. self.bboxes[:, 0] = w - self.bboxes[:, 0]
  275. self.segments[..., 0] = w - self.segments[..., 0]
  276. if self.keypoints is not None:
  277. self.keypoints[..., 0] = w - self.keypoints[..., 0]
  278. def clip(self, w, h):
  279. """Clips bounding boxes, segments, and keypoints values to stay within image boundaries."""
  280. ori_format = self._bboxes.format
  281. self.convert_bbox(format="xyxy")
  282. self.bboxes[:, [0, 2]] = self.bboxes[:, [0, 2]].clip(0, w)
  283. self.bboxes[:, [1, 3]] = self.bboxes[:, [1, 3]].clip(0, h)
  284. if ori_format != "xyxy":
  285. self.convert_bbox(format=ori_format)
  286. self.segments[..., 0] = self.segments[..., 0].clip(0, w)
  287. self.segments[..., 1] = self.segments[..., 1].clip(0, h)
  288. if self.keypoints is not None:
  289. self.keypoints[..., 0] = self.keypoints[..., 0].clip(0, w)
  290. self.keypoints[..., 1] = self.keypoints[..., 1].clip(0, h)
  291. def remove_zero_area_boxes(self):
  292. """Remove zero-area boxes, i.e. after clipping some boxes may have zero width or height."""
  293. good = self.bbox_areas > 0
  294. if not all(good):
  295. self._bboxes = self._bboxes[good]
  296. if len(self.segments):
  297. self.segments = self.segments[good]
  298. if self.keypoints is not None:
  299. self.keypoints = self.keypoints[good]
  300. return good
  301. def update(self, bboxes, segments=None, keypoints=None):
  302. """Updates instance variables."""
  303. self._bboxes = Bboxes(bboxes, format=self._bboxes.format)
  304. if segments is not None:
  305. self.segments = segments
  306. if keypoints is not None:
  307. self.keypoints = keypoints
  308. def __len__(self):
  309. """Return the length of the instance list."""
  310. return len(self.bboxes)
  311. @classmethod
  312. def concatenate(cls, instances_list: List["Instances"], axis=0) -> "Instances":
  313. """
  314. Concatenates a list of Instances objects into a single Instances object.
  315. Args:
  316. instances_list (List[Instances]): A list of Instances objects to concatenate.
  317. axis (int, optional): The axis along which the arrays will be concatenated. Defaults to 0.
  318. Returns:
  319. Instances: A new Instances object containing the concatenated bounding boxes,
  320. segments, and keypoints if present.
  321. Note:
  322. The `Instances` objects in the list should have the same properties, such as
  323. the format of the bounding boxes, whether keypoints are present, and if the
  324. coordinates are normalized.
  325. """
  326. assert isinstance(instances_list, (list, tuple))
  327. if not instances_list:
  328. return cls(np.empty(0))
  329. assert all(isinstance(instance, Instances) for instance in instances_list)
  330. if len(instances_list) == 1:
  331. return instances_list[0]
  332. use_keypoint = instances_list[0].keypoints is not None
  333. bbox_format = instances_list[0]._bboxes.format
  334. normalized = instances_list[0].normalized
  335. cat_boxes = np.concatenate([ins.bboxes for ins in instances_list], axis=axis)
  336. cat_segments = np.concatenate([b.segments for b in instances_list], axis=axis)
  337. cat_keypoints = np.concatenate([b.keypoints for b in instances_list], axis=axis) if use_keypoint else None
  338. return cls(cat_boxes, cat_segments, cat_keypoints, bbox_format, normalized)
  339. @property
  340. def bboxes(self):
  341. """Return bounding boxes."""
  342. return self._bboxes.bboxes