Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[feat] Augmentation Sequential with a list of bboxes as a batch (#1497)

Jian Shifcb9550320e0
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index ffb0fe216..d0957ab93 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -1,16 +1,12 @@
import warnings
from itertools import zip_longest
-from typing import cast, List, Optional, Tuple, Union
+from typing import Any, cast, List, Optional, Tuple, Union
import torch
-from kornia.augmentation.base import (
- _AugmentationBase,
- GeometricAugmentationBase2D,
- IntensityAugmentationBase2D,
- TensorWithTransformMat,
-)
+from kornia.augmentation.base import _AugmentationBase, GeometricAugmentationBase2D, IntensityAugmentationBase2D
from kornia.constants import DataKey
+from kornia.geometry.boxes import Boxes
from .base import SequentialBase
from .image import ImageSequential, ParamItem
@@ -20,6 +16,9 @@ from .video import VideoSequential
__all__ = ["AugmentationSequential"]
+AugmentationSequentialInput = Union[
+ torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor, torch.Tensor], Tuple[List[torch.Tensor], torch.Tensor]]
+
class AugmentationSequential(ImageSequential):
r"""AugmentationSequential for handling multiple input types like inputs, masks, keypoints at once.
@@ -228,12 +227,12 @@ class AugmentationSequential(ImageSequential):
return outputs
def __packup_output__( # type: ignore
- self, output: List[TensorWithTransformMat], label: Optional[torch.Tensor] = None
+ self, output: List[AugmentationSequentialInput], label: Optional[torch.Tensor] = None
) -> Union[
- TensorWithTransformMat,
- Tuple[TensorWithTransformMat, Optional[torch.Tensor]],
- List[TensorWithTransformMat],
- Tuple[List[TensorWithTransformMat], Optional[torch.Tensor]],
+ AugmentationSequentialInput,
+ Tuple[AugmentationSequentialInput, Optional[torch.Tensor]],
+ List[AugmentationSequentialInput],
+ Tuple[List[AugmentationSequentialInput], Optional[torch.Tensor]],
]:
if len(output) == 1 and isinstance(output, (tuple, list)) and self.return_label:
return output[0], label
@@ -243,36 +242,65 @@ class AugmentationSequential(ImageSequential):
return output, label
return output
+ def _validate_args_datakeys(self, *args: AugmentationSequentialInput, data_keys: List[DataKey]):
+ if len(args) != len(data_keys):
+ raise AssertionError(
+ f"The number of inputs must align with the number of data_keys. Got {len(args)} and {len(data_keys)}."
+ )
+ # TODO: validate args batching, and its consistency
+
+ def _arguments_preproc(self, *args: AugmentationSequentialInput, data_keys: List[DataKey]):
+ inp: List[Any] = []
+ for arg, dcate in zip(args, data_keys):
+ if DataKey.get(dcate) in [DataKey.INPUT, DataKey.MASK, DataKey.KEYPOINTS]:
+ inp.append(arg)
+ elif DataKey.get(dcate) in [DataKey.BBOX, DataKey.BBOX_XYXY, DataKey.BBOX_XYWH]:
+ if DataKey.get(dcate) in [DataKey.BBOX]:
+ mode = "vertices_plus"
+ elif DataKey.get(dcate) in [DataKey.BBOX_XYXY]:
+ mode = "xyxy"
+ elif DataKey.get(dcate) in [DataKey.BBOX_XYWH]:
+ mode = "xywh"
+ else:
+ raise ValueError(f"Unsupported mode `{DataKey.get(dcate).name}`.")
+ inp.append(Boxes.from_tensor(arg, mode=mode)) # type: ignore
+ else:
+ raise NotImplementedError(f"input type of {dcate} is not implemented.")
+ return inp
+
def forward( # type: ignore
self,
- *args: TensorWithTransformMat,
+ *args: AugmentationSequentialInput,
label: Optional[torch.Tensor] = None,
params: Optional[List[ParamItem]] = None,
data_keys: Optional[List[Union[str, int, DataKey]]] = None,
) -> Union[
- TensorWithTransformMat,
- Tuple[TensorWithTransformMat, Optional[torch.Tensor]],
- List[TensorWithTransformMat],
- Tuple[List[TensorWithTransformMat], Optional[torch.Tensor]],
+ AugmentationSequentialInput,
+ Tuple[AugmentationSequentialInput, Optional[torch.Tensor]],
+ List[AugmentationSequentialInput],
+ Tuple[List[AugmentationSequentialInput], Optional[torch.Tensor]],
]:
"""Compute multiple tensors simultaneously according to ``self.data_keys``."""
if data_keys is None:
- data_keys = cast(List[Union[str, int, DataKey]], self.data_keys)
+ _data_keys = self.data_keys
else:
- data_keys = [DataKey.get(inp) for inp in data_keys]
+ _data_keys = list(DataKey.get(inp) for inp in data_keys)
+ self._validate_args_datakeys(*args, data_keys=_data_keys)
- if len(args) != len(data_keys):
- raise AssertionError(
- f"The number of inputs must align with the number of data_keys. Got {len(args)} and {len(data_keys)}."
- )
+ args = self._arguments_preproc(*args, data_keys=_data_keys)
if params is None:
- if DataKey.INPUT in data_keys:
- _input = args[data_keys.index(DataKey.INPUT)]
- if isinstance(_input, (tuple, list)):
+ # image data must exist if params is not provided.
+ if DataKey.INPUT in _data_keys:
+ _input = args[_data_keys.index(DataKey.INPUT)]
+ # If (input, mat) received.
+ if isinstance(_input, (tuple,)):
inp = _input[0]
else:
inp = _input
+ if isinstance(inp, (tuple, list,)):
+ raise ValueError(f"`INPUT` should be a tensor but `{type(inp)}` received.")
+ # A video input shall be BCDHW while an image input shall be BCHW
if self.contains_video_sequential:
_, out_shape = self.autofill_dim(inp, dim_range=(3, 5))
else:
@@ -281,21 +309,29 @@ class AugmentationSequential(ImageSequential):
else:
raise ValueError("`params` must be provided whilst INPUT is not in data_keys.")
- outputs: List[TensorWithTransformMat] = [None] * len(data_keys) # type: ignore
- if DataKey.INPUT in data_keys:
- idx = data_keys.index(DataKey.INPUT)
- out = super().forward(args[idx], label, params=params)
+ outputs: List[AugmentationSequentialInput] = [None] * len(_data_keys) # type: ignore
+ # Forward the first image data to freeze the parameters.
+ if DataKey.INPUT in _data_keys:
+ idx = _data_keys.index(DataKey.INPUT)
+ _inp = args[idx]
+ _out = super().forward(_inp, label, params=params) # type: ignore
if self.return_label:
- input, label = cast(Tuple[TensorWithTransformMat, torch.Tensor], out)
+ _input, label = cast(Tuple[AugmentationSequentialInput, torch.Tensor], _out)
else:
- input = cast(TensorWithTransformMat, out)
- outputs[idx] = input
+ _input = cast(AugmentationSequentialInput, _out)
+ outputs[idx] = _input
self.return_label = self.return_label or label is not None or self.contains_label_operations(params)
- for idx, (input, dcate, out) in enumerate(zip(args, data_keys, outputs)):
+ for idx, (arg, dcate, out) in enumerate(zip(args, _data_keys, outputs)):
if out is not None:
continue
+ # Using tensors straight-away
+ if isinstance(arg, (Boxes,)):
+ input = arg.data # all boxes are in (B, N, 4, 2) format now.
+ else:
+ input = arg
+
for param in params:
module = self.get_submodule(param.name)
if dcate == DataKey.INPUT:
@@ -317,6 +353,11 @@ class AugmentationSequential(ImageSequential):
raise ValueError(f"Unsupported Sequential {module}.")
else:
raise NotImplementedError(f"data_key {dcate} is not implemented for {module}.")
- outputs[idx] = input
+
+ if isinstance(arg, (Boxes,)):
+ arg._data = input
+ outputs[idx] = arg.to_tensor()
+ else:
+ outputs[idx] = input
return self.__packup_output__(outputs, label)
diff --git a/kornia/augmentation/container/utils.py b/kornia/augmentation/container/utils.py
index 181744030..1378d7607 100644
--- a/kornia/augmentation/container/utils.py
+++ b/kornia/augmentation/container/utils.py
@@ -282,6 +282,15 @@ class MaskApplyInverse(ApplyInverseImpl):
return input
+class BBoxApplyInverse(ApplyInverseImpl):
+ """Apply and inverse transformations for bounding box tensors.
+
+ This is for transform boxes in the format (B, N, 4, 2).
+ """
+
+ apply_func = partial(transform_bbox, mode="xyxy", restore_coordinates=True)
+
+
class BBoxXYXYApplyInverse(ApplyInverseImpl):
"""Apply and inverse transformations for bounding box tensors.
@@ -399,10 +408,9 @@ class ApplyInverse:
return InputApplyInverse
if DataKey.get(dcate) in [DataKey.MASK]:
return MaskApplyInverse
- if DataKey.get(dcate) in [DataKey.BBOX, DataKey.BBOX_XYXY]:
- return BBoxXYXYApplyInverse
- if DataKey.get(dcate) in [DataKey.BBOX_XYWH]:
- return BBoxXYWHApplyInverse
+ if DataKey.get(dcate) in [DataKey.BBOX, DataKey.BBOX_XYXY, DataKey.BBOX_XYWH]:
+ # We are converting to (B, 4, 2) internally for all formats.
+ return BBoxApplyInverse
if DataKey.get(dcate) in [DataKey.KEYPOINTS]:
return KeypointsApplyInverse
raise NotImplementedError(f"input type of {dcate} is not implemented.")
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index 4a58c4a86..12abbfddd 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -436,13 +436,13 @@ def bbox_generator3d(
def transform_bbox(
trans_mat: torch.Tensor, boxes: torch.Tensor, mode: str = "xyxy", restore_coordinates: Optional[bool] = None
) -> torch.Tensor:
- r"""Function that applies a transformation matrix to a box or batch of boxes. Boxes must
- be a tensor of the shape (N, 4) or a batch of boxes (B, N, 4) and trans_mat must be a (3, 3)
- transformation matrix or a batch of transformation matrices (B, 3, 3)
+ r"""Apply a transformation matrix to a box or batch of boxes.
Args:
- trans_mat: The transformation matrix to be applied
- boxes: The boxes to be transformed
+ trans_mat: The transformation matrix to be applied with a shape of :math:`(3, 3)`
+ or batched as :math:`(B, 3, 3)`.
+ boxes: The boxes to be transformed with a common shape of :math:`(N, 4)` or batched as :math:`(B, N, 4)`, the
+ polygon shape of :math:`(B, N, 4, 2)` is also supported.
mode: The format in which the boxes are provided. If set to 'xyxy' the boxes are assumed to be in the format
``xmin, ymin, xmax, ymax``. If set to 'xywh' the boxes are assumed to be in the format
``xmin, ymin, width, height``
@@ -459,8 +459,8 @@ def transform_bbox(
if mode not in ("xyxy", "xywh"):
raise ValueError(f"Mode must be one of 'xyxy', 'xywh'. Got {mode}")
- # (B, 4, 2) shaped polygon boxes do not need to be restored.
- if restore_coordinates is None and boxes.shape[-2:] != torch.Size([4, 2]):
+ # (B, N, 4, 2) shaped polygon boxes do not need to be restored.
+ if restore_coordinates is None and not (boxes.shape[-2:] == torch.Size([4, 2])):
warnings.warn(
"Previous behaviour produces incorrect box coordinates if a flip transformation performed on boxes."
"The previous wrong behaviour has been corrected and will be removed in the future versions."
@@ -476,7 +476,7 @@ def transform_bbox(
transformed_boxes: torch.Tensor = transform_points(trans_mat, boxes.view(boxes.shape[0], -1, 2))
transformed_boxes = transformed_boxes.view_as(boxes)
- if (restore_coordinates is None or restore_coordinates) and boxes.shape[-2:] != torch.Size([4, 2]):
+ if (restore_coordinates is None or restore_coordinates) and not (boxes.shape[-2:] == torch.Size([4, 2])):
restored_boxes = transformed_boxes.clone()
# In case the boxes are flipped, we ensure it is ordered like left-top -> right-bot points
restored_boxes[..., 0] = torch.min(transformed_boxes[..., [0, 2]], dim=-1)[0]
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index e83c6b7db..19b64d32e 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -1,7 +1,8 @@
-from typing import Optional, Tuple
+from typing import cast, List, Optional, Tuple, Union
import torch
+from kornia.geometry.bbox import validate_bbox
from kornia.geometry.linalg import transform_points
__all__ = ["Boxes", "Boxes3D"]
@@ -11,6 +12,25 @@ def _is_floating_point_dtype(dtype: torch.dtype) -> bool:
return dtype in (torch.float16, torch.float32, torch.float64, torch.bfloat16, torch.half)
+def _merge_box_list(
+ boxes: List[torch.Tensor], method: str = "pad"
+) -> Tuple[torch.Tensor, List[int]]:
+ r"""Merge a list of boxes into one tensor.
+ """
+ if not all(box.shape[-2:] == torch.Size([4, 2]) and box.dim() == 3 for box in boxes):
+ raise TypeError(
+ f"Input boxes must be a list of (N, 4, 2) shaped. Got: {[box.shape for box in boxes]}.")
+
+ if method == "pad":
+ max_N = max(box.shape[0] for box in boxes)
+ stats = [max_N - box.shape[0] for box in boxes]
+ output = torch.nn.utils.rnn.pad_sequence(boxes, batch_first=True)
+ else:
+ raise NotImplementedError(f"`{method}` is not implemented.")
+
+ return output, stats
+
+
def _transform_boxes(boxes: torch.Tensor, M: torch.Tensor) -> torch.Tensor:
"""Transforms 3D and 2D in kornia format by applying the transformation matrix M. Boxes and the transformation
matrix could be batched or not.
@@ -55,6 +75,61 @@ def _boxes_to_polygons(
return polygons
+def _boxes_to_quadrilaterals(
+ boxes: torch.Tensor, mode: str = "xyxy", validate_boxes: bool = True
+) -> torch.Tensor:
+ """Convert from boxes to quadrilaterals."""
+ mode = mode.lower()
+
+ if mode.startswith("vertices"):
+ batched = boxes.ndim == 4
+ if not (3 <= boxes.ndim <= 4 and boxes.shape[-2:] == torch.Size([4, 2])):
+ raise ValueError(f"Boxes shape must be (N, 4, 2) or (B, N, 4, 2) when {mode} mode. Got {boxes.shape}.")
+ elif mode.startswith("xy"):
+ batched = boxes.ndim == 3
+ if not (2 <= boxes.ndim <= 3 and boxes.shape[-1] == 4):
+ raise ValueError(f"Boxes shape must be (N, 4) or (B, N, 4) when {mode} mode. Got {boxes.shape}.")
+ else:
+ raise ValueError(f"Unknown mode {mode}")
+
+ boxes = boxes if boxes.is_floating_point() else boxes.float()
+ boxes = boxes if batched else boxes.unsqueeze(0)
+
+ if mode.startswith("vertices"):
+ if mode == "vertices":
+ # Avoid passing reference
+ quadrilaterals = boxes.clone()
+ elif mode == "vertices_plus":
+ quadrilaterals = boxes.clone() # TODO: perform +1
+ else:
+ raise ValueError(f"Unknown mode {mode}")
+ validate_boxes or validate_bbox(quadrilaterals)
+ elif mode.startswith("xy"):
+ if mode == "xyxy":
+ height, width = boxes[..., 3] - boxes[..., 1], boxes[..., 2] - boxes[..., 0]
+ elif mode == "xyxy_plus":
+ height, width = boxes[..., 3] - boxes[..., 1] + 1, boxes[..., 2] - boxes[..., 0] + 1
+ elif mode == "xywh":
+ height, width = boxes[..., 3], boxes[..., 2]
+ else:
+ raise ValueError(f"Unknown mode {mode}")
+
+ if validate_boxes:
+ if (width <= 0).any():
+ raise ValueError("Some boxes have negative widths or 0.")
+ if (height <= 0).any():
+ raise ValueError("Some boxes have negative heights or 0.")
+
+ xmin, ymin = boxes[..., 0], boxes[..., 1]
+ quadrilaterals = _boxes_to_polygons(xmin, ymin, width, height)
+ else:
+ raise ValueError(f"Unknown mode {mode}")
+
+ quadrilaterals = quadrilaterals if batched else quadrilaterals.squeeze(0)
+
+ return quadrilaterals
+
+
def _boxes3d_to_polygons3d(
xmin: torch.Tensor,
ymin: torch.Tensor,
@@ -86,14 +161,17 @@ def _boxes3d_to_polygons3d(
return polygons3d
+# NOTE: Cannot jit with Union types with torch <= 0.10
+# @torch.jit.script
class Boxes:
r"""2D boxes containing N or BxN boxes.
Args:
- boxes: 2D boxes, shape of :math:`(N,4,2)` or :math:`(B,N,4,2)`. See below for more details.
+ boxes: 2D boxes, shape of :math:`(N, 4, 2)`, :math:`(B, N, 4, 2)` or a list of :math:`(N, 4, 2)`.
+ See below for more details.
raise_if_not_floating_point: flag to control floating point casting behaviour when `boxes` is not a floating
point tensor. True to raise an error when `boxes` isn't a floating point tensor, False to cast to float.
+ mode: the box format of the input boxes.
Note:
**2D boxes format** is defined as a floating data type tensor of shape ``Nx4x2`` or ``BxNx4x2``
@@ -102,7 +180,16 @@ class Boxes:
``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``. Examples of
`quadrilaterals <https://en.wikipedia.org/wiki/Quadrilateral>`_ are rectangles, rhombus and trapezoids.
"""
- def __init__(self, boxes: torch.Tensor, raise_if_not_floating_point: bool = True) -> None:
+ def __init__(
+ self, boxes: Union[torch.Tensor, List[torch.Tensor]], raise_if_not_floating_point: bool = True,
+ mode: str = "vertices_plus"
+ ) -> None:
+
+ self._N: Optional[List[int]] = None
+
+ if isinstance(boxes, list):
+ boxes, self._N = _merge_box_list(boxes)
+
if not isinstance(boxes, torch.Tensor):
raise TypeError(f"Input boxes is not a Tensor. Got: {type(boxes)}.")
@@ -120,7 +207,8 @@ class Boxes:
if not (3 <= boxes.ndim <= 4 and boxes.shape[-2:] == (4, 2)):
raise ValueError(f"Boxes shape must be (N, 4, 2) or (B, N, 4, 2). Got {boxes.shape}.")
- self._boxes = boxes
+ self._data = boxes
+ self._mode = mode
def get_boxes_shape(self) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Compute boxes heights and widths.
@@ -135,24 +223,34 @@ class Boxes:
>>> boxes.get_boxes_shape()
(tensor([[1., 1.]]), tensor([[1., 2.]]))
"""
- boxes_xywh = self.to_tensor(mode='xywh')
+ boxes_xywh = cast(torch.Tensor, self.to_tensor("xywh", as_padded_sequence=True))
widths, heights = boxes_xywh[..., 2], boxes_xywh[..., 3]
return heights, widths
@classmethod
- def from_tensor(cls, boxes: torch.Tensor, mode: str = "xyxy", validate_boxes: bool = True) -> "Boxes":
+ def from_tensor(
+ cls, boxes: Union[torch.Tensor, List[torch.Tensor]], mode: str = "xyxy", validate_boxes: bool = True
+ ) -> "Boxes":
r"""Helper method to easily create :class:`Boxes` from boxes stored in another format.
Args:
- boxes: 2D boxes, shape of :math:`(N,4)` or :math:`(B,N,4)`.
+ boxes: 2D boxes, shape of :math:`(N, 4)`, :math:`(B, N, 4)`, :math:`(N, 4, 2)` or :math:`(B, N, 4, 2)`.
mode: The format in which the boxes are provided.
* 'xyxy': boxes are assumed to be in the format ``xmin, ymin, xmax, ymax`` where ``width = xmax - xmin``
- and ``height = ymax - ymin``.
+ and ``height = ymax - ymin``. With shape :math:`(N, 4)`, :math:`(B, N, 4)`.
* 'xyxy_plus': similar to 'xyxy' mode but where box width and length are defined as
``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``.
+ With shape :math:`(N, 4)`, :math:`(B, N, 4)`.
* 'xywh': boxes are assumed to be in the format ``xmin, ymin, width, height`` where
- ``width = xmax - xmin`` and ``height = ymax - ymin``.
+ ``width = xmax - xmin`` and ``height = ymax - ymin``. With shape :math:`(N, 4)`, :math:`(B, N, 4)`.
+ * 'vertices': boxes are defined by their vertices points in the following ``clockwise`` order:
+ *top-left, top-right, bottom-right, bottom-left*. Vertices coordinates are in (x,y) order. Finally,
+ box width and height are defined as ``width = xmax - xmin`` and ``height = ymax - ymin``.
+ With shape :math:`(N, 4, 2)` or :math:`(B, N, 4, 2)`.
+ * 'vertices_plus': similar to 'vertices' mode but where box width and length are defined as
+ ``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``. ymin + 1``.
+ With shape :math:`(N, 4, 2)` or :math:`(B, N, 4, 2)`.
validate_boxes: check if boxes are valid rectangles or not. Valid rectangles are those with width
and height >= 1 (>= 2 when mode ends with '_plus' suffix).
@@ -163,7 +261,7 @@ class Boxes:
Examples:
>>> boxes_xyxy = torch.as_tensor([[0, 3, 1, 4], [5, 1, 8, 4]])
>>> boxes = Boxes.from_tensor(boxes_xyxy, mode='xyxy')
- >>> boxes._boxes # (2, 4, 2)
+ >>> boxes.data # (2, 4, 2)
tensor([[[0., 3.],
[0., 3.],
[0., 3.],
@@ -174,37 +272,19 @@ class Boxes:
[7., 3.],
[5., 3.]]])
"""
- if not (2 <= boxes.ndim <= 3 and boxes.shape[-1] == 4):
- raise ValueError(f"Boxes shape must be (N, 4) or (B, N, 4). Got {boxes.shape}.")
-
- batched = boxes.ndim == 3
- boxes = boxes if batched else boxes.unsqueeze(0)
- boxes = boxes if boxes.is_floating_point() else boxes.float()
-
- xmin, ymin = boxes[..., 0], boxes[..., 1]
- mode = mode.lower()
- if mode == "xyxy":
- height, width = boxes[..., 3] - boxes[..., 1], boxes[..., 2] - boxes[..., 0]
- elif mode == "xyxy_plus":
- height, width = boxes[..., 3] - boxes[..., 1] + 1, boxes[..., 2] - boxes[..., 0] + 1
- elif mode == "xywh":
- height, width = boxes[..., 3], boxes[..., 2]
+ quadrilaterals: Union[torch.Tensor, List[torch.Tensor]]
+ if isinstance(boxes, (torch.Tensor)):
+ quadrilaterals = _boxes_to_quadrilaterals(boxes, mode=mode, validate_boxes=validate_boxes)
else:
- raise ValueError(f"Unknown mode {mode}")
+ quadrilaterals = [_boxes_to_quadrilaterals(box, mode, validate_boxes) for box in boxes]
- if validate_boxes:
- if (width <= 0).any():
- raise ValueError("Some boxes have negative widths or 0.")
- if (height <= 0).any():
- raise ValueError("Some boxes have negative heights or 0.")
-
- quadrilaterals = _boxes_to_polygons(xmin, ymin, width, height)
- quadrilaterals = quadrilaterals if batched else quadrilaterals.squeeze(0)
# Due to some torch.jit.script bug (at least <= 1.9), you need to pass all arguments to __init__ when
# constructing the class from inside of a method.
- return cls(quadrilaterals, False)
+ return cls(quadrilaterals, False, mode)
- def to_tensor(self, mode: str = "xyxy") -> torch.Tensor:
+ def to_tensor(
+ self, mode: Optional[str] = None, as_padded_sequence: bool = False
+ ) -> Union[torch.Tensor, List[torch.Tensor]]:
r"""Cast :class:`Boxes` to a tensor. ``mode`` controls which 2D boxes format should be use to represent boxes
in the tensor.
@@ -222,6 +302,8 @@ class Boxes:
box width and height are defined as ``width = xmax - xmin`` and ``height = ymax - ymin``.
* 'vertices_plus': similar to 'vertices' mode but where box width and length are defined as
``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``. ymin + 1``.
+ as_padded_sequence: whether to keep the pads for a list of boxes. This parameter is only valid
+ if the boxes are from a box list.
Returns:
Boxes tensor in the ``mode`` format. The shape depends with the ``mode`` value:
@@ -234,14 +316,20 @@ class Boxes:
>>> boxes = Boxes.from_tensor(boxes_xyxy)
>>> assert (boxes_xyxy == boxes.to_tensor(mode='xyxy')).all()
"""
- batched_boxes = self._boxes if self._is_batch else self._boxes.unsqueeze(0)
+ batched_boxes = self._data if self._is_batched else self._data.unsqueeze(0)
+
+ boxes: Union[torch.Tensor, List[torch.Tensor]]
# Create boxes in xyxy_plus format.
boxes = torch.stack([batched_boxes.amin(dim=-2), batched_boxes.amax(dim=-2)], dim=-2).view(
batched_boxes.shape[0], batched_boxes.shape[1], 4
)
+ if mode is None:
+ mode = self.mode
+
mode = mode.lower()
+
if mode in ("xyxy", "xyxy_plus"):
pass
elif mode in ("xywh", "vertices", "vertices_plus"):
@@ -258,7 +346,11 @@ class Boxes:
if mode.startswith('vertices'):
boxes = _boxes_to_polygons(boxes[..., 0], boxes[..., 1], boxes[..., 2], boxes[..., 3])
- boxes = boxes if self._is_batch else boxes.squeeze(0)
+ if self._N is not None and not as_padded_sequence:
+ boxes = list(torch.nn.functional.pad(
+ o, (len(o.shape) - 1) * [0, 0] + [0, - n]) for o, n in zip(boxes, self._N))
+ else:
+ boxes = boxes if self._is_batched else boxes.squeeze(0)
return boxes
def to_mask(self, height: int, width: int) -> torch.Tensor:
@@ -289,20 +381,20 @@ class Boxes:
[0., 1., 1., 1., 1.],
[0., 0., 0., 0., 0.]]])
"""
- if self._boxes.requires_grad:
+ if self._data.requires_grad:
raise RuntimeError(
"Boxes.to_tensor isn't differentiable. Please, create boxes from tensors with `requires_grad=False`."
)
- if self._is_batch: # (B, N, 4, 2)
+ if self._is_batched: # (B, N, 4, 2)
mask = torch.zeros(
- (self._boxes.shape[0], self._boxes.shape[1], height, width), dtype=self.dtype, device=self.device
+ (self._data.shape[0], self._data.shape[1], height, width), dtype=self.dtype, device=self.device
)
else: # (N, 4, 2)
- mask = torch.zeros((self._boxes.shape[0], height, width), dtype=self.dtype, device=self.device)
+ mask = torch.zeros((self._data.shape[0], height, width), dtype=self.dtype, device=self.device)
# Boxes coordinates can be outside the image size after transforms. Clamp values to the image size
- clipped_boxes_xyxy = self.to_tensor("xyxy")
+ clipped_boxes_xyxy = cast(torch.Tensor, self.to_tensor("xyxy", as_padded_sequence=True))
clipped_boxes_xyxy[..., ::2].clamp_(0, width)
clipped_boxes_xyxy[..., 1::2].clamp_(0, height)
@@ -329,9 +421,9 @@ class Boxes:
# Due to some torch.jit.script bug (at least <= 1.9), you need to pass all arguments to __init__ when
# constructing the class from inside of a method.
- transformed_boxes = _transform_boxes(self._boxes, M)
+ transformed_boxes = _transform_boxes(self._data, M)
if inplace:
- self._boxes = transformed_boxes
+ self._data = transformed_boxes
return self
return Boxes(transformed_boxes, False)
@@ -341,25 +433,33 @@ class Boxes:
return self.transform_boxes(M, inplace=True)
@property
- def _is_batch(self) -> bool:
- return self._boxes.ndim == 4
+ def _is_batched(self) -> bool:
+ return self._data.ndim == 4
+
+ @property
+ def data(self) -> torch.Tensor:
+ return self._data
+
+ @property
+ def mode(self) -> str:
+ return self._mode
@property
def device(self) -> torch.device:
"""Returns boxes device."""
- return self._boxes.device
+ return self._data.device
@property
def dtype(self) -> torch.dtype:
"""Returns boxes dtype."""
- return self._boxes.dtype
+ return self._data.dtype
def to(self, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> "Boxes":
"""Like :func:`torch.nn.Module.to()` method."""
# In torchscript, dtype is a int and not a class. https://github.com/pytorch/pytorch/issues/51941
if dtype is not None and not _is_floating_point_dtype(dtype):
raise ValueError("Boxes must be in floating point")
- self._boxes = self._boxes.to(device=device, dtype=dtype)
+ self._data = self._data.to(device=device, dtype=dtype)
return self
@@ -397,7 +497,7 @@ class Boxes3D:
if not (3 <= boxes.ndim <= 4 and boxes.shape[-2:] == (8, 3)):
raise ValueError(f"3D bbox shape must be (N, 8, 3) or (B, N, 8, 3). Got {boxes.shape}.")
- self._boxes = boxes
+ self._data = boxes
def get_boxes_shape(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
r"""Compute boxes heights and widths.
@@ -441,7 +541,7 @@ class Boxes3D:
Examples:
>>> boxes_xyzxyz = torch.as_tensor([[0, 3, 6, 1, 4, 8], [5, 1, 3, 8, 4, 9]])
>>> boxes = Boxes3D.from_tensor(boxes_xyzxyz, mode='xyzxyz')
- >>> boxes._boxes # (2, 8, 3)
+ >>> boxes.data # (2, 8, 3)
tensor([[[0., 3., 6.],
[0., 3., 6.],
[0., 3., 6.],
@@ -532,13 +632,13 @@ class Boxes3D:
>>> boxes = Boxes3D.from_tensor(boxes_xyzxyz, mode='xyzxyz')
>>> assert (boxes.to_tensor(mode='xyzxyz') == boxes_xyzxyz).all()
"""
- if self._boxes.requires_grad:
+ if self._data.requires_grad:
raise RuntimeError("Boxes3D.to_tensor doesn't support computing gradients since they aren't accurate. "
"Please, create boxes from tensors with `requires_grad=False`. "
"This is a known bug. Help is needed to fix it. For more information, "
"see https://github.com/kornia/kornia/issues/1396.")
- batched_boxes = self._boxes if self._is_batch else self._boxes.unsqueeze(0)
+ batched_boxes = self._data if self._is_batched else self._data.unsqueeze(0)
# Create boxes in xyzxyz_plus format.
boxes = torch.stack([batched_boxes.amin(dim=-2), batched_boxes.amax(dim=-2)], dim=-2).view(
@@ -568,7 +668,7 @@ class Boxes3D:
boxes = _boxes3d_to_polygons3d(xmin, ymin, zmin, width, height, depth)
- boxes = boxes if self._is_batch else boxes.squeeze(0)
+ boxes = boxes if self._is_batched else boxes.squeeze(0)
return boxes
def to_mask(self, depth: int, height: int, width: int) -> torch.Tensor:
@@ -622,20 +722,20 @@ class Boxes3D:
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]]]])
"""
- if self._boxes.requires_grad:
+ if self._data.requires_grad:
raise RuntimeError(
"Boxes.to_tensor isn't differentiable. Please, create boxes from tensors with `requires_grad=False`."
)
- if self._is_batch: # (B, N, 8, 3)
+ if self._is_batched: # (B, N, 8, 3)
mask = torch.zeros(
- (self._boxes.shape[0], self._boxes.shape[1], depth, height, width),
- dtype=self._boxes.dtype,
- device=self._boxes.device,
+ (self._data.shape[0], self._data.shape[1], depth, height, width),
+ dtype=self._data.dtype,
+ device=self._data.device,
)
else: # (N, 8, 3)
mask = torch.zeros(
- (self._boxes.shape[0], depth, height, width), dtype=self._boxes.dtype, device=self._boxes.device
+ (self._data.shape[0], depth, height, width), dtype=self._data.dtype, device=self._data.device
)
# Boxes coordinates can be outside the image size after transforms. Clamp values to the image size
@@ -671,9 +771,9 @@ class Boxes3D:
# Due to some torch.jit.script bug (at least <= 1.9), you need to pass all arguments to __init__ when
# constructing the class from inside of a method.
- transformed_boxes = _transform_boxes(self._boxes, M)
+ transformed_boxes = _transform_boxes(self._data, M)
if inplace:
- self._boxes = transformed_boxes
+ self._data = transformed_boxes
return self
return Boxes3D(transformed_boxes, False)
@@ -683,23 +783,27 @@ class Boxes3D:
return self.transform_boxes(M, inplace=True)
@property
- def _is_batch(self) -> bool:
- return self._boxes.ndim == 4
+ def _is_batched(self) -> bool:
+ return self._data.ndim == 4
+
+ @property
+ def data(self) -> torch.Tensor:
+ return self._data
@property
def device(self) -> torch.device:
"""Returns boxes device."""
- return self._boxes.device
+ return self._data.device
@property
def dtype(self) -> torch.dtype:
"""Returns boxes dtype."""
- return self._boxes.dtype
+ return self._data.dtype
def to(self, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> "Boxes3D":
"""Like :func:`torch.nn.Module.to()` method."""
# In torchscript, dtype is a int and not a class. https://github.com/pytorch/pytorch/issues/51941
if dtype is not None and not _is_floating_point_dtype(dtype):
raise ValueError("Boxes must be in floating point")
- self._boxes = self._boxes.to(device=device, dtype=dtype)
+ self._data = self._data.to(device=device, dtype=dtype)
return self
diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.py
index a1969e213..a2708861f 100644
--- a/test/augmentation/test_container.py
+++ b/test/augmentation/test_container.py
@@ -282,10 +282,10 @@ class TestAugmentationSequential:
bbox = torch.tensor([[[355, 10], [660, 10], [660, 250], [355, 250]]], device=device, dtype=dtype)
expected_bbox_vertical_flip = torch.tensor(
- [[[355, 499], [660, 499], [660, 259], [355, 259]]], device=device, dtype=dtype
+ [[[355, 259], [660, 259], [660, 499], [355, 499]]], device=device, dtype=dtype
)
expected_bbox_horizontal_flip = torch.tensor(
- [[[664, 10], [359, 10], [359, 250], [664, 250]]], device=device, dtype=dtype
+ [[[359, 10], [664, 10], [664, 250], [359, 250]]], device=device, dtype=dtype
)
aug_ver = K.AugmentationSequential(
@@ -469,6 +469,18 @@ class TestAugmentationSequential:
def test_inverse_and_forward_return_transform(self, random_apply, device, dtype):
inp = torch.randn(1, 3, 1000, 500, device=device, dtype=dtype)
bbox = torch.tensor([[[355, 10], [660, 10], [660, 250], [355, 250]]], device=device, dtype=dtype)
+ bbox_2 = [
+ # torch.tensor([[[355, 10], [660, 10], [660, 250], [355, 250]]], device=device, dtype=dtype),
+ torch.tensor([
+ [[355, 10], [660, 10], [660, 250], [355, 250]],
+ [[355, 10], [660, 10], [660, 250], [355, 250]]
+ ], device=device, dtype=dtype)
+ ]
+ bbox_wh = torch.tensor([[[30, 40, 100, 100]]], device=device, dtype=dtype)
+ bbox_wh_2 = [
+ # torch.tensor([[30, 40, 100, 100]], device=device, dtype=dtype),
+ torch.tensor([[30, 40, 100, 100], [30, 40, 100, 100]], device=device, dtype=dtype)
+ ]
keypoints = torch.tensor([[[465, 115], [545, 116]]], device=device, dtype=dtype)
mask = bbox_to_mask(
torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), 1000, 500
@@ -482,19 +494,19 @@ class TestAugmentationSequential:
),
K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0, return_transform=True),
K.RandomAffine(360, p=1.0, return_transform=True),
- data_keys=["input", "mask", "bbox", "keypoints"],
+ data_keys=["input", "mask", "bbox", "keypoints", "bbox", "BBOX_XYWH", "BBOX_XYWH"],
random_apply=random_apply,
)
with pytest.raises(Exception): # No parameters available for inversing.
- aug.inverse(inp, mask, bbox, keypoints)
+ aug.inverse(inp, mask, bbox, keypoints, bbox_2, bbox_wh, bbox_wh_2)
- out = aug(inp, mask, bbox, keypoints)
+ out = aug(inp, mask, bbox, keypoints, bbox_2, bbox_wh, bbox_wh_2)
assert out[0][0].shape == inp.shape
assert out[1].shape == mask.shape
assert out[2].shape == bbox.shape
assert out[3].shape == keypoints.shape
- reproducibility_test((inp, mask, bbox, keypoints), aug)
+ reproducibility_test((inp, mask, bbox, keypoints, bbox_2, bbox_wh, bbox_wh_2), aug)
@pytest.mark.jit
@pytest.mark.skip(reason="turn off due to Union Type")
diff --git a/test/geometry/test_boxes.py b/test/geometry/test_boxes.py
index 8dc18a8e9..a7446ad57 100644
--- a/test/geometry/test_boxes.py
+++ b/test/geometry/test_boxes.py
@@ -87,9 +87,9 @@ class TestBoxes2D:
expected_box = torch.as_tensor([[[1, 2], [2, 2], [2, 3], [1, 3]]], device=device, dtype=dtype).view(*shape, 2)
- boxes_xyxy = Boxes.from_tensor(box_xyxy, mode='xyxy')._boxes
- boxes_xyxy_plus = Boxes.from_tensor(box_xyxy_plus, mode='xyxy_plus')._boxes
- boxes_xywh = Boxes.from_tensor(box_xywh, mode='xywh')._boxes
+ boxes_xyxy = Boxes.from_tensor(box_xyxy, mode='xyxy').data
+ boxes_xyxy_plus = Boxes.from_tensor(box_xyxy_plus, mode='xyxy_plus').data
+ boxes_xywh = Boxes.from_tensor(box_xywh, mode='xywh').data
assert boxes_xyxy.shape == expected_box.shape
assert_allclose(boxes_xyxy, expected_box)
@@ -138,21 +138,39 @@ class TestBoxes2D:
boxes_vertices = box.to_tensor(mode='vertices')
boxes_vertices_plus = box.to_tensor(mode='vertices_plus')
- assert boxes_xyxy.shape == expected_box_xyxy.shape
+ assert boxes_xyxy.shape == expected_box_xyxy.shape # type: ignore
assert_allclose(boxes_xyxy, expected_box_xyxy)
- assert boxes_xyxy_plus.shape == expected_box_xyxy_plus.shape
+ assert boxes_xyxy_plus.shape == expected_box_xyxy_plus.shape # type: ignore
assert_allclose(boxes_xyxy_plus, expected_box_xyxy_plus)
- assert boxes_xywh.shape == expected_box_xywh.shape
+ assert boxes_xywh.shape == expected_box_xywh.shape # type: ignore
assert_allclose(boxes_xywh, expected_box_xywh)
- assert boxes_vertices.shape == expected_vertices.shape
+ assert boxes_vertices.shape == expected_vertices.shape # type: ignore
assert_allclose(boxes_vertices, expected_vertices)
- assert boxes_vertices_plus.shape == expected_vertices_plus.shape
+ assert boxes_vertices_plus.shape == expected_vertices_plus.shape # type: ignore
assert_allclose(boxes_vertices_plus, expected_vertices_plus)
+ @pytest.mark.parametrize('mode', ['xyxy', 'xyxy_plus', 'xywh', 'vertices', 'vertices_plus'])
+ def test_boxes_list_to_tensor_list(self, mode, device, dtype):
+ src_1 = [
+ torch.as_tensor([[[2, 2], [2, 3], [1, 3], [1, 2]]], device=device, dtype=dtype),
+ torch.as_tensor([
+ [[2, 2], [2, 3], [1, 3], [1, 2]], [[2, 2], [2, 3], [1, 3], [1, 2]]
+ ], device=device, dtype=dtype)
+ ]
+ src_2 = [
+ torch.as_tensor([[1, 1, 5, 5]], device=device, dtype=dtype),
+ torch.as_tensor([[1, 1, 5, 5], [1, 1, 5, 5]], device=device, dtype=dtype)
+ ]
+ src = src_1 if mode in ['vertices', 'vertices_plus'] else src_2
+ box = Boxes.from_tensor(src, mode=mode)
+ out = box.to_tensor(mode)
+ assert out[0].shape == src[0].shape
+ assert out[1].shape == src[1].shape
+
def test_boxes_to_mask(self, device, dtype):
t_box1 = torch.tensor(
[[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype
@@ -219,18 +237,18 @@ class TestBoxes2D:
def test_to(self, device, dtype):
boxes = Boxes.from_tensor(torch.as_tensor([[1, 2, 3, 4]], device='cpu', dtype=torch.float32))
- assert boxes.to(device=device)._boxes.device == device
- assert boxes.to(dtype=dtype)._boxes.dtype == dtype
+ assert boxes.to(device=device).data.device == device
+ assert boxes.to(dtype=dtype).data.dtype == dtype
boxes_moved = boxes.to(device, dtype)
assert boxes_moved is boxes # to is an inplace op.
- assert boxes_moved._boxes.device == device, boxes_moved._boxes.dtype == dtype
+ assert boxes_moved.data.device == device, boxes_moved.data.dtype == dtype
def test_gradcheck(self, device, dtype):
def apply_boxes_method(tensor: torch.Tensor, method: str, **kwargs):
boxes = Boxes(tensor)
result = getattr(boxes, method)(**kwargs)
- return result._boxes if isinstance(result, Boxes) else result
+ return result.data if isinstance(result, Boxes) else result
t_boxes1 = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
@@ -250,10 +268,10 @@ class TestBoxes2D:
)
assert gradcheck(partial(apply_boxes_method, method='get_boxes_shape'), (t_boxes1,), raise_exception=True)
assert gradcheck(
- lambda x: Boxes.from_tensor(x, mode='xyxy_plus')._boxes, (t_boxes_xyxy,), raise_exception=True
+ lambda x: Boxes.from_tensor(x, mode='xyxy_plus').data, (t_boxes_xyxy,), raise_exception=True
)
assert gradcheck(
- lambda x: Boxes.from_tensor(x, mode='xywh')._boxes, (t_boxes_xyxy1,), raise_exception=True
+ lambda x: Boxes.from_tensor(x, mode='xywh').data, (t_boxes_xyxy1,), raise_exception=True
)
@@ -269,7 +287,7 @@ class TestTransformBoxes2D:
trans_mat = torch.tensor([[[-1.0, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
transformed_boxes = boxes.transform_boxes(trans_mat)
- assert_allclose(transformed_boxes._boxes, expected_boxes._boxes, atol=1e-4, rtol=1e-4)
+ assert_allclose(transformed_boxes.data, expected_boxes.data, atol=1e-4, rtol=1e-4)
# inplace check
assert transformed_boxes is not boxes
@@ -284,7 +302,7 @@ class TestTransformBoxes2D:
trans_mat = torch.tensor([[[-1.0, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
transformed_boxes = boxes.transform_boxes_(trans_mat)
- assert_allclose(transformed_boxes._boxes, expected_boxes._boxes, atol=1e-4, rtol=1e-4)
+ assert_allclose(transformed_boxes.data, expected_boxes.data, atol=1e-4, rtol=1e-4)
# inplace check
assert transformed_boxes is boxes
@@ -335,7 +353,7 @@ class TestTransformBoxes2D:
expected_boxes = Boxes.from_tensor(expected_boxes_xyxy, validate_boxes=False)
out = boxes.transform_boxes(trans_mat)
- assert_allclose(out._boxes, expected_boxes._boxes, atol=1e-4, rtol=1e-4)
+ assert_allclose(out.data, expected_boxes.data, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device, dtype):
# Define boxes in XYXY format for simplicity.
@@ -354,12 +372,12 @@ class TestTransformBoxes2D:
trans_mat = torch.tensor([[[-1.0, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
trans_mat = utils.tensor_to_gradcheck_var(trans_mat)
- t_boxes = utils.tensor_to_gradcheck_var(boxes._boxes)
+ t_boxes = utils.tensor_to_gradcheck_var(boxes.data)
def _wrapper_transform_boxes(quadrilaterals, M):
boxes = Boxes(quadrilaterals)
boxes = boxes.transform_boxes(M)
- return boxes._boxes
+ return boxes.data
assert gradcheck(_wrapper_transform_boxes, (t_boxes, trans_mat), raise_exception=True)
@@ -482,9 +500,9 @@ class TestBbox3D:
dtype=dtype,
).view(*shape[:-1], 8, 3)
- kornia_xyzxyz = Boxes3D.from_tensor(box_xyzxyz, mode='xyzxyz')._boxes
- kornia_xyzxyz_plus = Boxes3D.from_tensor(box_xyzxyz_plus, mode='xyzxyz_plus')._boxes
- kornia_xyzwhd = Boxes3D.from_tensor(box_xyzwhd, mode='xyzwhd')._boxes
+ kornia_xyzxyz = Boxes3D.from_tensor(box_xyzxyz, mode='xyzxyz').data
+ kornia_xyzxyz_plus = Boxes3D.from_tensor(box_xyzxyz_plus, mode='xyzxyz_plus').data
+ kornia_xyzwhd = Boxes3D.from_tensor(box_xyzwhd, mode='xyzwhd').data
assert kornia_xyzxyz.shape == expected_box.shape
assert_allclose(kornia_xyzxyz, expected_box)
@@ -691,19 +709,19 @@ class TestBbox3D:
def test_to(self, device, dtype):
boxes = Boxes3D.from_tensor(torch.as_tensor([[1, 2, 3, 4, 5, 6]], device='cpu', dtype=torch.float32))
- assert boxes.to(device=device)._boxes.device == device
- assert boxes.to(dtype=dtype)._boxes.dtype == dtype
+ assert boxes.to(device=device).data.device == device
+ assert boxes.to(dtype=dtype).data.dtype == dtype
boxes_moved = boxes.to(device, dtype)
assert boxes_moved is boxes # to is an inplace op.
- assert boxes_moved._boxes.device == device, boxes_moved._boxes.dtype == dtype
+ assert boxes_moved.data.device == device, boxes_moved.data.dtype == dtype
def test_gradcheck(self, device, dtype):
# Uncomment when enabling gradient checks
# def apply_boxes_method(tensor: torch.Tensor, method: str, **kwargs):
# boxes = Boxes3D(tensor)
# result = getattr(boxes, method)(**kwargs)
- # return result._boxes if isinstance(result, Boxes3D) else result
+ # return result.data if isinstance(result, Boxes3D) else result
t_boxes1 = torch.tensor(
[[[0, 1, 2], [10, 1, 2], [10, 21, 2], [0, 21, 2], [0, 1, 32], [10, 1, 32], [10, 21, 32], [0, 21, 32]]],
@@ -730,10 +748,10 @@ class TestBbox3D:
# )
# assert gradcheck(partial(apply_boxes_method, method='get_boxes_shape'), (t_boxes1,), raise_exception=True)
assert gradcheck(
- lambda x: Boxes3D.from_tensor(x, mode='xyzxyz_plus')._boxes, (t_boxes_xyzxyz,), raise_exception=True
+ lambda x: Boxes3D.from_tensor(x, mode='xyzxyz_plus').data, (t_boxes_xyzxyz,), raise_exception=True
)
assert gradcheck(
- lambda x: Boxes3D.from_tensor(x, mode='xyzwhd')._boxes, (t_boxes_xyzxyz1,), raise_exception=True
+ lambda x: Boxes3D.from_tensor(x, mode='xyzwhd').data, (t_boxes_xyzxyz1,), raise_exception=True
)
@@ -757,7 +775,7 @@ class TestTransformBoxes3D:
)
transformed_boxes = boxes.transform_boxes(trans_mat)
- assert_allclose(transformed_boxes._boxes, expected_boxes._boxes, atol=1e-4, rtol=1e-4)
+ assert_allclose(transformed_boxes.data, expected_boxes.data, atol=1e-4, rtol=1e-4)
# inplace check
assert transformed_boxes is not boxes
@@ -780,7 +798,7 @@ class TestTransformBoxes3D:
)
transformed_boxes = boxes.transform_boxes_(trans_mat)
- assert_allclose(transformed_boxes._boxes, expected_boxes._boxes, atol=1e-4, rtol=1e-4)
+ assert_allclose(transformed_boxes.data, expected_boxes.data, atol=1e-4, rtol=1e-4)
# inplace check
assert transformed_boxes is boxes
@@ -831,7 +849,7 @@ class TestTransformBoxes3D:
expected_boxes = Boxes3D.from_tensor(expected_boxes_xyzxyz, validate_boxes=False)
out = boxes.transform_boxes(trans_mat)
- assert_allclose(out._boxes, expected_boxes._boxes, atol=1e-4, rtol=1e-4)
+ assert_allclose(out.data, expected_boxes.data, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device, dtype):
# Define boxes in XYZXYZ format for simplicity.
@@ -854,11 +872,11 @@ class TestTransformBoxes3D:
)
trans_mat = utils.tensor_to_gradcheck_var(trans_mat)
- t_boxes = utils.tensor_to_gradcheck_var(boxes._boxes)
+ t_boxes = utils.tensor_to_gradcheck_var(boxes.data)
def _wrapper_transform_boxes(hexahedrons, M):
boxes = Boxes3D(hexahedrons)
boxes = boxes.transform_boxes(M)
- return boxes._boxes
+ return boxes.data
assert gradcheck(_wrapper_transform_boxes, (t_boxes, trans_mat), raise_exception=True)