Args: box: can be a k-tuple, k-list or an Nxk array/tensor, where k = 4 or 5 from_mode, to_mode (BoxMode) Returns: The converted box of the same type.
(box: _RawBoxType, from_mode: "BoxMode", to_mode: "BoxMode")
| 42 | |
| 43 | @staticmethod |
| 44 | def convert(box: _RawBoxType, from_mode: "BoxMode", to_mode: "BoxMode") -> _RawBoxType: |
| 45 | """ |
| 46 | Args: |
| 47 | box: can be a k-tuple, k-list or an Nxk array/tensor, where k = 4 or 5 |
| 48 | from_mode, to_mode (BoxMode) |
| 49 | |
| 50 | Returns: |
| 51 | The converted box of the same type. |
| 52 | """ |
| 53 | if from_mode == to_mode: |
| 54 | return box |
| 55 | |
| 56 | original_type = type(box) |
| 57 | is_numpy = isinstance(box, np.ndarray) |
| 58 | single_box = isinstance(box, (list, tuple)) |
| 59 | if single_box: |
| 60 | assert len(box) == 4 or len(box) == 5, ( |
| 61 | "BoxMode.convert takes either a k-tuple/list or an Nxk array/tensor," |
| 62 | " where k == 4 or 5" |
| 63 | ) |
| 64 | arr = torch.tensor(box)[None, :] |
| 65 | else: |
| 66 | # avoid modifying the input box |
| 67 | if is_numpy: |
| 68 | arr = torch.from_numpy(np.asarray(box)).clone() |
| 69 | else: |
| 70 | arr = box.clone() |
| 71 | |
| 72 | assert to_mode not in [BoxMode.XYXY_REL, BoxMode.XYWH_REL] and from_mode not in [ |
| 73 | BoxMode.XYXY_REL, |
| 74 | BoxMode.XYWH_REL, |
| 75 | ], "Relative mode not yet supported!" |
| 76 | |
| 77 | if from_mode == BoxMode.XYWHA_ABS and to_mode == BoxMode.XYXY_ABS: |
| 78 | assert ( |
| 79 | arr.shape[-1] == 5 |
| 80 | ), "The last dimension of input shape must be 5 for XYWHA format" |
| 81 | original_dtype = arr.dtype |
| 82 | arr = arr.double() |
| 83 | |
| 84 | w = arr[:, 2] |
| 85 | h = arr[:, 3] |
| 86 | a = arr[:, 4] |
| 87 | c = torch.abs(torch.cos(a * math.pi / 180.0)) |
| 88 | s = torch.abs(torch.sin(a * math.pi / 180.0)) |
| 89 | # This basically computes the horizontal bounding rectangle of the rotated box |
| 90 | new_w = c * w + s * h |
| 91 | new_h = c * h + s * w |
| 92 | |
| 93 | # convert center to top-left corner |
| 94 | arr[:, 0] -= new_w / 2.0 |
| 95 | arr[:, 1] -= new_h / 2.0 |
| 96 | # bottom-right corner |
| 97 | arr[:, 2] = arr[:, 0] + new_w |
| 98 | arr[:, 3] = arr[:, 1] + new_h |
| 99 | |
| 100 | arr = arr[:, :4].to(dtype=original_dtype) |
| 101 | elif from_mode == BoxMode.XYWH_ABS and to_mode == BoxMode.XYWHA_ABS: |