Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

boxes.py 18 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
  1. from typing import Tuple
  2. import torch
  3. import torchvision
  4. from torch import Tensor
  5. from torchvision.extension import _assert_has_ops
  6. from ..utils import _log_api_usage_once
  7. from ._box_convert import (
  8. _box_cxcywh_to_xyxy,
  9. _box_cxcywhr_to_xywhr,
  10. _box_xywh_to_xyxy,
  11. _box_xywhr_to_cxcywhr,
  12. _box_xywhr_to_xyxyxyxy,
  13. _box_xyxy_to_cxcywh,
  14. _box_xyxy_to_xywh,
  15. _box_xyxyxyxy_to_xywhr,
  16. )
  17. from ._utils import _upcast
  18. def nms(boxes: Tensor, scores: Tensor, iou_threshold: float) -> Tensor:
  19. """
  20. Performs non-maximum suppression (NMS) on the boxes according
  21. to their intersection-over-union (IoU).
  22. NMS iteratively removes lower scoring boxes which have an
  23. IoU greater than ``iou_threshold`` with another (higher scoring)
  24. box.
  25. If multiple boxes have the exact same score and satisfy the IoU
  26. criterion with respect to a reference box, the selected box is
  27. not guaranteed to be the same between CPU and GPU. This is similar
  28. to the behavior of argsort in PyTorch when repeated values are present.
  29. Args:
  30. boxes (Tensor[N, 4])): boxes to perform NMS on. They
  31. are expected to be in ``(x1, y1, x2, y2)`` format with ``0 <= x1 < x2`` and
  32. ``0 <= y1 < y2``.
  33. scores (Tensor[N]): scores for each one of the boxes
  34. iou_threshold (float): discards all overlapping boxes with IoU > iou_threshold
  35. Returns:
  36. Tensor: int64 tensor with the indices of the elements that have been kept
  37. by NMS, sorted in decreasing order of scores
  38. """
  39. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  40. _log_api_usage_once(nms)
  41. _assert_has_ops()
  42. return torch.ops.torchvision.nms(boxes, scores, iou_threshold)
  43. def batched_nms(
  44. boxes: Tensor,
  45. scores: Tensor,
  46. idxs: Tensor,
  47. iou_threshold: float,
  48. ) -> Tensor:
  49. """
  50. Performs non-maximum suppression in a batched fashion.
  51. Each index value correspond to a category, and NMS
  52. will not be applied between elements of different categories.
  53. Args:
  54. boxes (Tensor[N, 4]): boxes where NMS will be performed. They
  55. are expected to be in ``(x1, y1, x2, y2)`` format with ``0 <= x1 < x2`` and
  56. ``0 <= y1 < y2``.
  57. scores (Tensor[N]): scores for each one of the boxes
  58. idxs (Tensor[N]): indices of the categories for each one of the boxes.
  59. iou_threshold (float): discards all overlapping boxes with IoU > iou_threshold
  60. Returns:
  61. Tensor: int64 tensor with the indices of the elements that have been kept by NMS, sorted
  62. in decreasing order of scores
  63. """
  64. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  65. _log_api_usage_once(batched_nms)
  66. # Benchmarks that drove the following thresholds are at
  67. # https://github.com/pytorch/vision/issues/1311#issuecomment-781329339
  68. # and https://github.com/pytorch/vision/pull/8925
  69. if boxes.numel() > (4000 if boxes.device.type == "cpu" else 100_000) and not torchvision._is_tracing():
  70. return _batched_nms_vanilla(boxes, scores, idxs, iou_threshold)
  71. else:
  72. return _batched_nms_coordinate_trick(boxes, scores, idxs, iou_threshold)
  73. @torch.jit._script_if_tracing
  74. def _batched_nms_coordinate_trick(
  75. boxes: Tensor,
  76. scores: Tensor,
  77. idxs: Tensor,
  78. iou_threshold: float,
  79. ) -> Tensor:
  80. # strategy: in order to perform NMS independently per class,
  81. # we add an offset to all the boxes. The offset is dependent
  82. # only on the class idx, and is large enough so that boxes
  83. # from different classes do not overlap
  84. if boxes.numel() == 0:
  85. return torch.empty((0,), dtype=torch.int64, device=boxes.device)
  86. max_coordinate = boxes.max()
  87. offsets = idxs.to(boxes) * (max_coordinate + torch.tensor(1).to(boxes))
  88. boxes_for_nms = boxes + offsets[:, None]
  89. keep = nms(boxes_for_nms, scores, iou_threshold)
  90. return keep
  91. @torch.jit._script_if_tracing
  92. def _batched_nms_vanilla(
  93. boxes: Tensor,
  94. scores: Tensor,
  95. idxs: Tensor,
  96. iou_threshold: float,
  97. ) -> Tensor:
  98. # Based on Detectron2 implementation, just manually call nms() on each class independently
  99. keep_mask = torch.zeros_like(scores, dtype=torch.bool)
  100. for class_id in torch.unique(idxs):
  101. curr_indices = torch.where(idxs == class_id)[0]
  102. curr_keep_indices = nms(boxes[curr_indices], scores[curr_indices], iou_threshold)
  103. keep_mask[curr_indices[curr_keep_indices]] = True
  104. keep_indices = torch.where(keep_mask)[0]
  105. return keep_indices[scores[keep_indices].sort(descending=True)[1]]
  106. def remove_small_boxes(boxes: Tensor, min_size: float) -> Tensor:
  107. """
  108. Remove every box from ``boxes`` which contains at least one side length
  109. that is smaller than ``min_size``.
  110. .. note::
  111. For sanitizing a :class:`~torchvision.tv_tensors.BoundingBoxes` object, consider using
  112. the transform :func:`~torchvision.transforms.v2.SanitizeBoundingBoxes` instead.
  113. Args:
  114. boxes (Tensor[N, 4]): boxes in ``(x1, y1, x2, y2)`` format
  115. with ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
  116. min_size (float): minimum size
  117. Returns:
  118. Tensor[K]: indices of the boxes that have both sides
  119. larger than ``min_size``
  120. """
  121. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  122. _log_api_usage_once(remove_small_boxes)
  123. ws, hs = boxes[:, 2] - boxes[:, 0], boxes[:, 3] - boxes[:, 1]
  124. keep = (ws >= min_size) & (hs >= min_size)
  125. keep = torch.where(keep)[0]
  126. return keep
  127. def clip_boxes_to_image(boxes: Tensor, size: Tuple[int, int]) -> Tensor:
  128. """
  129. Clip boxes so that they lie inside an image of size ``size``.
  130. .. note::
  131. For clipping a :class:`~torchvision.tv_tensors.BoundingBoxes` object, consider using
  132. the transform :func:`~torchvision.transforms.v2.ClampBoundingBoxes` instead.
  133. Args:
  134. boxes (Tensor[N, 4]): boxes in ``(x1, y1, x2, y2)`` format
  135. with ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
  136. size (Tuple[height, width]): size of the image
  137. Returns:
  138. Tensor[N, 4]: clipped boxes
  139. """
  140. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  141. _log_api_usage_once(clip_boxes_to_image)
  142. dim = boxes.dim()
  143. boxes_x = boxes[..., 0::2]
  144. boxes_y = boxes[..., 1::2]
  145. height, width = size
  146. if torchvision._is_tracing():
  147. boxes_x = torch.max(boxes_x, torch.tensor(0, dtype=boxes.dtype, device=boxes.device))
  148. boxes_x = torch.min(boxes_x, torch.tensor(width, dtype=boxes.dtype, device=boxes.device))
  149. boxes_y = torch.max(boxes_y, torch.tensor(0, dtype=boxes.dtype, device=boxes.device))
  150. boxes_y = torch.min(boxes_y, torch.tensor(height, dtype=boxes.dtype, device=boxes.device))
  151. else:
  152. boxes_x = boxes_x.clamp(min=0, max=width)
  153. boxes_y = boxes_y.clamp(min=0, max=height)
  154. clipped_boxes = torch.stack((boxes_x, boxes_y), dim=dim)
  155. return clipped_boxes.reshape(boxes.shape)
  156. def box_convert(boxes: Tensor, in_fmt: str, out_fmt: str) -> Tensor:
  157. """
  158. Converts :class:`torch.Tensor` boxes from a given ``in_fmt`` to ``out_fmt``.
  159. .. note::
  160. For converting a :class:`torch.Tensor` or a :class:`~torchvision.tv_tensors.BoundingBoxes` object
  161. between different formats,
  162. consider using :func:`~torchvision.transforms.v2.functional.convert_bounding_box_format` instead.
  163. Or see the corresponding transform :func:`~torchvision.transforms.v2.ConvertBoundingBoxFormat`.
  164. Supported ``in_fmt`` and ``out_fmt`` strings are:
  165. ``'xyxy'``: boxes are represented via corners, x1, y1 being top left and x2, y2 being bottom right.
  166. This is the format that torchvision utilities expect.
  167. ``'xywh'``: boxes are represented via corner, width and height, x1, y2 being top left, w, h being width and height.
  168. ``'cxcywh'``: boxes are represented via centre, width and height, cx, cy being center of box, w, h
  169. being width and height.
  170. ``'xywhr'``: boxes are represented via corner, width and height, x1, y2 being top left, w, h being width and height.
  171. r is rotation angle w.r.t to the box center by :math:`|r|` degrees counter clock wise in the image plan
  172. ``'cxcywhr'``: boxes are represented via centre, width and height, cx, cy being center of box, w, h
  173. being width and height.
  174. r is rotation angle w.r.t to the box center by :math:`|r|` degrees counter clock wise in the image plan
  175. ``'xyxyxyxy'``: boxes are represented via corners, x1, y1 being top left, x2, y2 bottom right,
  176. x3, y3 bottom left, and x4, y4 top right.
  177. Args:
  178. boxes (Tensor[N, K]): boxes which will be converted. K is the number of coordinates (4 for unrotated bounding boxes, 5 or 8 for rotated bounding boxes)
  179. in_fmt (str): Input format of given boxes. Supported formats are ['xyxy', 'xywh', 'cxcywh', 'xywhr', 'cxcywhr', 'xyxyxyxy'].
  180. out_fmt (str): Output format of given boxes. Supported formats are ['xyxy', 'xywh', 'cxcywh', 'xywhr', 'cxcywhr', 'xyxyxyxy']
  181. Returns:
  182. Tensor[N, K]: Boxes into converted format.
  183. """
  184. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  185. _log_api_usage_once(box_convert)
  186. allowed_fmts = (
  187. "xyxy",
  188. "xywh",
  189. "cxcywh",
  190. "xywhr",
  191. "cxcywhr",
  192. "xyxyxyxy",
  193. )
  194. if in_fmt not in allowed_fmts or out_fmt not in allowed_fmts:
  195. raise ValueError(f"Unsupported Bounding Box Conversions for given in_fmt {in_fmt} and out_fmt {out_fmt}")
  196. if in_fmt == out_fmt:
  197. return boxes.clone()
  198. e = (in_fmt, out_fmt)
  199. if e == ("xywh", "xyxy"):
  200. boxes = _box_xywh_to_xyxy(boxes)
  201. elif e == ("cxcywh", "xyxy"):
  202. boxes = _box_cxcywh_to_xyxy(boxes)
  203. elif e == ("xyxy", "xywh"):
  204. boxes = _box_xyxy_to_xywh(boxes)
  205. elif e == ("xyxy", "cxcywh"):
  206. boxes = _box_xyxy_to_cxcywh(boxes)
  207. elif e == ("xywh", "cxcywh"):
  208. boxes = _box_xywh_to_xyxy(boxes)
  209. boxes = _box_xyxy_to_cxcywh(boxes)
  210. elif e == ("cxcywh", "xywh"):
  211. boxes = _box_cxcywh_to_xyxy(boxes)
  212. boxes = _box_xyxy_to_xywh(boxes)
  213. elif e == ("cxcywhr", "xywhr"):
  214. boxes = _box_cxcywhr_to_xywhr(boxes)
  215. elif e == ("xywhr", "cxcywhr"):
  216. boxes = _box_xywhr_to_cxcywhr(boxes)
  217. elif e == ("cxcywhr", "xyxyxyxy"):
  218. boxes = _box_cxcywhr_to_xywhr(boxes).to(boxes.dtype)
  219. boxes = _box_xywhr_to_xyxyxyxy(boxes)
  220. elif e == ("xyxyxyxy", "cxcywhr"):
  221. boxes = _box_xyxyxyxy_to_xywhr(boxes).to(boxes.dtype)
  222. boxes = _box_xywhr_to_cxcywhr(boxes)
  223. elif e == ("xywhr", "xyxyxyxy"):
  224. boxes = _box_xywhr_to_xyxyxyxy(boxes)
  225. elif e == ("xyxyxyxy", "xywhr"):
  226. boxes = _box_xyxyxyxy_to_xywhr(boxes)
  227. else:
  228. raise NotImplementedError(f"Unsupported Bounding Box Conversions for given in_fmt {e[0]} and out_fmt {e[1]}")
  229. return boxes
  230. def box_area(boxes: Tensor) -> Tensor:
  231. """
  232. Computes the area of a set of bounding boxes, which are specified by their
  233. (x1, y1, x2, y2) coordinates.
  234. Args:
  235. boxes (Tensor[N, 4]): boxes for which the area will be computed. They
  236. are expected to be in (x1, y1, x2, y2) format with
  237. ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
  238. Returns:
  239. Tensor[N]: the area for each box
  240. """
  241. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  242. _log_api_usage_once(box_area)
  243. boxes = _upcast(boxes)
  244. return (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
  245. # implementation from https://github.com/kuangliu/torchcv/blob/master/torchcv/utils/box.py
  246. # with slight modifications
  247. def _box_inter_union(boxes1: Tensor, boxes2: Tensor) -> Tuple[Tensor, Tensor]:
  248. area1 = box_area(boxes1)
  249. area2 = box_area(boxes2)
  250. lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2]
  251. rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2]
  252. wh = _upcast(rb - lt).clamp(min=0) # [N,M,2]
  253. inter = wh[:, :, 0] * wh[:, :, 1] # [N,M]
  254. union = area1[:, None] + area2 - inter
  255. return inter, union
  256. def box_iou(boxes1: Tensor, boxes2: Tensor) -> Tensor:
  257. """
  258. Return intersection-over-union (Jaccard index) between two sets of boxes.
  259. Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with
  260. ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
  261. Args:
  262. boxes1 (Tensor[N, 4]): first set of boxes
  263. boxes2 (Tensor[M, 4]): second set of boxes
  264. Returns:
  265. Tensor[N, M]: the NxM matrix containing the pairwise IoU values for every element in boxes1 and boxes2
  266. """
  267. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  268. _log_api_usage_once(box_iou)
  269. inter, union = _box_inter_union(boxes1, boxes2)
  270. iou = inter / union
  271. return iou
  272. # Implementation adapted from https://github.com/facebookresearch/detr/blob/master/util/box_ops.py
  273. def generalized_box_iou(boxes1: Tensor, boxes2: Tensor) -> Tensor:
  274. """
  275. Return generalized intersection-over-union (Jaccard index) between two sets of boxes.
  276. Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with
  277. ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
  278. Args:
  279. boxes1 (Tensor[N, 4]): first set of boxes
  280. boxes2 (Tensor[M, 4]): second set of boxes
  281. Returns:
  282. Tensor[N, M]: the NxM matrix containing the pairwise generalized IoU values
  283. for every element in boxes1 and boxes2
  284. """
  285. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  286. _log_api_usage_once(generalized_box_iou)
  287. inter, union = _box_inter_union(boxes1, boxes2)
  288. iou = inter / union
  289. lti = torch.min(boxes1[:, None, :2], boxes2[:, :2])
  290. rbi = torch.max(boxes1[:, None, 2:], boxes2[:, 2:])
  291. whi = _upcast(rbi - lti).clamp(min=0) # [N,M,2]
  292. areai = whi[:, :, 0] * whi[:, :, 1]
  293. return iou - (areai - union) / areai
  294. def complete_box_iou(boxes1: Tensor, boxes2: Tensor, eps: float = 1e-7) -> Tensor:
  295. """
  296. Return complete intersection-over-union (Jaccard index) between two sets of boxes.
  297. Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with
  298. ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
  299. Args:
  300. boxes1 (Tensor[N, 4]): first set of boxes
  301. boxes2 (Tensor[M, 4]): second set of boxes
  302. eps (float, optional): small number to prevent division by zero. Default: 1e-7
  303. Returns:
  304. Tensor[N, M]: the NxM matrix containing the pairwise complete IoU values
  305. for every element in boxes1 and boxes2
  306. """
  307. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  308. _log_api_usage_once(complete_box_iou)
  309. boxes1 = _upcast(boxes1)
  310. boxes2 = _upcast(boxes2)
  311. diou, iou = _box_diou_iou(boxes1, boxes2, eps)
  312. w_pred = boxes1[:, None, 2] - boxes1[:, None, 0]
  313. h_pred = boxes1[:, None, 3] - boxes1[:, None, 1]
  314. w_gt = boxes2[:, 2] - boxes2[:, 0]
  315. h_gt = boxes2[:, 3] - boxes2[:, 1]
  316. v = (4 / (torch.pi**2)) * torch.pow(torch.atan(w_pred / h_pred) - torch.atan(w_gt / h_gt), 2)
  317. with torch.no_grad():
  318. alpha = v / (1 - iou + v + eps)
  319. return diou - alpha * v
  320. def distance_box_iou(boxes1: Tensor, boxes2: Tensor, eps: float = 1e-7) -> Tensor:
  321. """
  322. Return distance intersection-over-union (Jaccard index) between two sets of boxes.
  323. Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with
  324. ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
  325. Args:
  326. boxes1 (Tensor[N, 4]): first set of boxes
  327. boxes2 (Tensor[M, 4]): second set of boxes
  328. eps (float, optional): small number to prevent division by zero. Default: 1e-7
  329. Returns:
  330. Tensor[N, M]: the NxM matrix containing the pairwise distance IoU values
  331. for every element in boxes1 and boxes2
  332. """
  333. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  334. _log_api_usage_once(distance_box_iou)
  335. boxes1 = _upcast(boxes1)
  336. boxes2 = _upcast(boxes2)
  337. diou, _ = _box_diou_iou(boxes1, boxes2, eps=eps)
  338. return diou
  339. def _box_diou_iou(boxes1: Tensor, boxes2: Tensor, eps: float = 1e-7) -> Tuple[Tensor, Tensor]:
  340. iou = box_iou(boxes1, boxes2)
  341. lti = torch.min(boxes1[:, None, :2], boxes2[:, :2])
  342. rbi = torch.max(boxes1[:, None, 2:], boxes2[:, 2:])
  343. whi = _upcast(rbi - lti).clamp(min=0) # [N,M,2]
  344. diagonal_distance_squared = (whi[:, :, 0] ** 2) + (whi[:, :, 1] ** 2) + eps
  345. # centers of boxes
  346. x_p = (boxes1[:, 0] + boxes1[:, 2]) / 2
  347. y_p = (boxes1[:, 1] + boxes1[:, 3]) / 2
  348. x_g = (boxes2[:, 0] + boxes2[:, 2]) / 2
  349. y_g = (boxes2[:, 1] + boxes2[:, 3]) / 2
  350. # The distance between boxes' centers squared.
  351. centers_distance_squared = (_upcast((x_p[:, None] - x_g[None, :])) ** 2) + (
  352. _upcast((y_p[:, None] - y_g[None, :])) ** 2
  353. )
  354. # The distance IoU is the IoU penalized by a normalized
  355. # distance between boxes' centers squared.
  356. return iou - (centers_distance_squared / diagonal_distance_squared), iou
  357. def masks_to_boxes(masks: torch.Tensor) -> torch.Tensor:
  358. """
  359. Compute the bounding boxes around the provided masks.
  360. Returns a [N, 4] tensor containing bounding boxes. The boxes are in ``(x1, y1, x2, y2)`` format with
  361. ``0 <= x1 <= x2`` and ``0 <= y1 <= y2``.
  362. .. warning::
  363. In most cases the output will guarantee ``x1 < x2`` and ``y1 < y2``. But
  364. if the input is degenerate, e.g. if a mask is a single row or a single
  365. column, then the output may have x1 = x2 or y1 = y2.
  366. Args:
  367. masks (Tensor[N, H, W]): masks to transform where N is the number of masks
  368. and (H, W) are the spatial dimensions.
  369. Returns:
  370. Tensor[N, 4]: bounding boxes
  371. """
  372. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  373. _log_api_usage_once(masks_to_boxes)
  374. if masks.numel() == 0:
  375. return torch.zeros((0, 4), device=masks.device, dtype=torch.float)
  376. n = masks.shape[0]
  377. bounding_boxes = torch.zeros((n, 4), device=masks.device, dtype=torch.float)
  378. for index, mask in enumerate(masks):
  379. y, x = torch.where(mask != 0)
  380. bounding_boxes[index, 0] = torch.min(x)
  381. bounding_boxes[index, 1] = torch.min(y)
  382. bounding_boxes[index, 2] = torch.max(x)
  383. bounding_boxes[index, 3] = torch.max(y)
  384. return bounding_boxes
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...