π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Add boxes V2 as discussed in #1142 (superseed #1177) (#1304)
hal-31467112ed5734d
diff --git a/docs/source/geometry.boxes.rst b/docs/source/geometry.boxes.rstnew file mode 100644index 000000000..a9dd4ad94--- /dev/null+++ b/docs/source/geometry.boxes.rst@@ -0,0 +1,7 @@+kornia.geometry.boxes+=======================++Module with useful functionalities for 2D and 3D bounding boxes manipulation.++.. automodule:: kornia.geometry.boxes+ :members:diff --git a/docs/source/geometry.rst b/docs/source/geometry.rstindex ec41c73c6..d3853c1e0 100644--- a/docs/source/geometry.rst+++ b/docs/source/geometry.rst@@ -45,6 +45,7 @@ transforms, camera, conversions, linalg and depth. We next describe each of them:maxdepth: 3geometry.bbox+ geometry.boxesgeometry.calibrationgeometry.camerageometry.conversionsdiff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.pynew file mode 100644index 000000000..e83c6b7db--- /dev/null+++ b/kornia/geometry/boxes.py@@ -0,0 +1,705 @@+from typing import Optional, Tuple++import torch++from kornia.geometry.linalg import transform_points++__all__ = ["Boxes", "Boxes3D"]+++def _is_floating_point_dtype(dtype: torch.dtype) -> bool:+ return dtype in (torch.float16, torch.float32, torch.float64, torch.bfloat16, torch.half)+++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.++ Args:+ boxes: 2D quadrilaterals or 3D hexahedrons in kornia format.+ M: the transformation matrix of shape :math:`(3, 3)` or :math:`(B, 3, 3)` for 2D and :math:`(4, 4)` or+ :math:`(B, 4, 4)` for 3D hexahedron.+ """+ M = M if M.is_floating_point() else M.float()++ # Work with batch as kornia.transform_points only supports a batch of points.+ boxes_per_batch, n_points_per_box, coordinates_dimension = boxes.shape[-3:]+ points = boxes.view(-1, n_points_per_box * boxes_per_batch, coordinates_dimension)+ M = M if M.ndim == 3 else M.unsqueeze(0)++ if points.shape[0] != M.shape[0]:+ raise ValueError(+ f"Batch size mismatch. Got {points.shape[0]} for boxes and {M.shape[0]} for the transformation matrix."+ )++ transformed_boxes: torch.Tensor = transform_points(M, points)+ transformed_boxes = transformed_boxes.view_as(boxes)+ return transformed_boxes+++def _boxes_to_polygons(+ xmin: torch.Tensor, ymin: torch.Tensor, width: torch.Tensor, height: torch.Tensor+) -> torch.Tensor:+ if not xmin.ndim == ymin.ndim == width.ndim == height.ndim == 2:+ raise ValueError("We expect to create a batch of 2D boxes (quadrilaterals) in vertices format (B, N, 4, 2)")++ # Create (B,N,4,2) with all points in top left position of boxes+ polygons = torch.zeros((xmin.shape[0], xmin.shape[1], 4, 2), device=xmin.device, dtype=xmin.dtype)+ polygons[..., 0] = xmin.unsqueeze(-1)+ polygons[..., 1] = ymin.unsqueeze(-1)+ # Shift top-right, bottom-right, bottom-left points to the right coordinates+ polygons[..., 1, 0] += width - 1 # Top right+ polygons[..., 2, 0] += width - 1 # Bottom right+ polygons[..., 2, 1] += height - 1 # Bottom right+ polygons[..., 3, 1] += height - 1 # Bottom left+ return polygons+++def _boxes3d_to_polygons3d(+ xmin: torch.Tensor,+ ymin: torch.Tensor,+ zmin: torch.Tensor,+ width: torch.Tensor,+ height: torch.Tensor,+ depth: torch.Tensor,+) -> torch.Tensor:+ if not xmin.ndim == ymin.ndim == zmin.ndim == width.ndim == height.ndim == depth.ndim == 2:+ raise ValueError("We expect to create a batch of 3D boxes (hexahedrons) in vertices format (B, N, 8, 3)")++ # Front+ # Create (B,N,4,3) with all points in front top left position of boxes+ front_vertices = torch.zeros((xmin.shape[0], xmin.shape[1], 4, 3), device=xmin.device, dtype=xmin.dtype)+ front_vertices[..., 0] = xmin.unsqueeze(-1)+ front_vertices[..., 1] = ymin.unsqueeze(-1)+ front_vertices[..., 2] = zmin.unsqueeze(-1)+ # Shift front-top-right, front-bottom-right, front-bottom-left points to the right coordinates+ front_vertices[..., 1, 0] += width - 1 # Top right+ front_vertices[..., 2, 0] += width - 1 # Bottom right+ front_vertices[..., 2, 1] += height - 1 # Bottom right+ front_vertices[..., 3, 1] += height - 1 # Bottom left++ # Back+ back_vertices = front_vertices.clone()+ back_vertices[..., 2] += depth.unsqueeze(-1) - 1++ polygons3d = torch.cat([front_vertices, back_vertices], dim=-2)+ return polygons3d+++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.+ 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.++ Note:+ **2D boxes format** is defined as a floating data type tensor of shape ``Nx4x2`` or ``BxNx4x2``+ where each box is a `quadrilateral <https://en.wikipedia.org/wiki/Quadrilateral>`_ defined by it's 4 vertices+ coordinates (A, B, C, D). Coordinates must be in ``x, y`` order. The height and width of a box is defined as+ ``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:+ if not isinstance(boxes, torch.Tensor):+ raise TypeError(f"Input boxes is not a Tensor. Got: {type(boxes)}.")++ if not boxes.is_floating_point():+ if raise_if_not_floating_point:+ raise ValueError(f"Coordinates must be in floating point. Got {boxes.dtype}")++ boxes = boxes.float()++ if len(boxes.shape) == 0:+ # Use reshape, so we don't end up creating a new tensor that does not depend on+ # the inputs (and consequently confuses jit)+ boxes = boxes.reshape((-1, 4))++ 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++ def get_boxes_shape(self) -> Tuple[torch.Tensor, torch.Tensor]:+ r"""Compute boxes heights and widths.++ Returns:+ - Boxes heights, shape of :math:`(N,)` or :math:`(B,N)`.+ - Boxes widths, shape of :math:`(N,)` or :math:`(B,N)`.++ Example:+ >>> boxes_xyxy = torch.tensor([[[1,1,2,2],[1,1,3,2]]])+ >>> boxes = Boxes.from_tensor(boxes_xyxy)+ >>> boxes.get_boxes_shape()+ (tensor([[1., 1.]]), tensor([[1., 2.]]))+ """+ boxes_xywh = self.to_tensor(mode='xywh')+ 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":+ 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)`.+ 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``.+ * 'xyxy_plus': similar to 'xyxy' mode but where box width and length are defined as+ ``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``.+ * 'xywh': boxes are assumed to be in the format ``xmin, ymin, width, height`` where+ ``width = xmax - xmin`` and ``height = ymax - ymin``.++ 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).++ Returns:+ :class:`Boxes` class containing the original `boxes` in the format specified by ``mode``.++ 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)+ tensor([[[0., 3.],+ [0., 3.],+ [0., 3.],+ [0., 3.]],+ <BLANKLINE>+ [[5., 1.],+ [7., 1.],+ [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]+ 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.")++ 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)++ def to_tensor(self, mode: str = "xyxy") -> torch.Tensor:+ r"""Cast :class:`Boxes` to a tensor. ``mode`` controls which 2D boxes format should be use to represent boxes+ in the tensor.++ Args:+ mode: the output box format. It could be:++ * 'xyxy': boxes are defined as ``xmin, ymin, xmax, ymax`` where ``width = xmax - xmin`` and+ ``height = ymax - ymin``.+ * 'xyxy_plus': similar to 'xyxy' mode but where box width and length are defined as+ ``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``.+ * 'xywh': boxes are defined as ``xmin, ymin, width, height`` where ``width = xmax - xmin``+ and ``height = ymax - ymin``.+ * '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``.+ * '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``.++ Returns:+ Boxes tensor in the ``mode`` format. The shape depends with the ``mode`` value:++ * 'vertices' or 'verticies_plus': :math:`(N, 4, 2)` or :math:`(B, N, 4, 2)`.+ * Any other value: :math:`(N, 4)` or :math:`(B, N, 4)`.++ Examples:+ >>> boxes_xyxy = torch.as_tensor([[0, 3, 1, 4], [5, 1, 8, 4]])+ >>> 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)++ # 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+ )++ mode = mode.lower()+ if mode in ("xyxy", "xyxy_plus"):+ pass+ elif mode in ("xywh", "vertices", "vertices_plus"):+ height, width = boxes[..., 3] - boxes[..., 1] + 1, boxes[..., 2] - boxes[..., 0] + 1+ boxes[..., 2] = width+ boxes[..., 3] = height+ else:+ raise ValueError(f"Unknown mode {mode}")++ if mode in ("xyxy", "vertices"):+ offset = torch.as_tensor([0, 0, 1, 1], device=boxes.device, dtype=boxes.dtype)+ boxes = boxes + offset++ 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)+ return boxes++ def to_mask(self, height: int, width: int) -> torch.Tensor:+ """Convert 2D boxes to masks. Covered area is 1 and the remaining is 0.++ Args:+ height: height of the masked image/images.+ width: width of the masked image/images.++ Returns:+ the output mask tensor, shape of :math:`(N, width, height)` or :math:`(B,N, width, height)` and dtype of+ :func:`Boxes.dtype` (it can be any floating point dtype).++ Note:+ It is currently non-differentiable.++ Examples:+ >>> boxes = Boxes(torch.tensor([[ # Equivalent to boxes = Boxes.from_tensor([[1,1,4,3]])+ ... [1., 1.],+ ... [4., 1.],+ ... [4., 3.],+ ... [1., 3.],+ ... ]])) # 1x4x2+ >>> boxes.to_mask(5, 5)+ tensor([[[0., 0., 0., 0., 0.],+ [0., 1., 1., 1., 1.],+ [0., 1., 1., 1., 1.],+ [0., 1., 1., 1., 1.],+ [0., 0., 0., 0., 0.]]])+ """+ if self._boxes.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)+ mask = torch.zeros(+ (self._boxes.shape[0], self._boxes.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)++ # 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[..., ::2].clamp_(0, width)+ clipped_boxes_xyxy[..., 1::2].clamp_(0, height)++ # Reshape mask to (BxN, H, W) and boxes to (BxN, 4) to iterate over all of them.+ # Cast boxes coordinates to be integer to use them as indexes. Use round to handle decimal values.+ for mask_channel, box_xyxy in zip(mask.view(-1, height, width), clipped_boxes_xyxy.view(-1, 4).round().int()):+ # Mask channel dimensions: (height, width)+ mask_channel[box_xyxy[1] : box_xyxy[3], box_xyxy[0] : box_xyxy[2]] = 1++ return mask++ def transform_boxes(self, M: torch.Tensor, inplace: bool = False) -> "Boxes":+ r"""Apply a transformation matrix to the 2D boxes.++ Args:+ M: The transformation matrix to be applied, shape of :math:`(3, 3)` or :math:`(B, 3, 3)`.+ inplace: do transform in-place and return self.++ Returns:+ The transformed boxes.+ """+ if not 2 <= M.ndim <= 3 or M.shape[-2:] != (3, 3):+ raise ValueError(f"The transformation matrix shape must be (3, 3) or (B, 3, 3). Got {M.shape}.")++ # 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)+ if inplace:+ self._boxes = transformed_boxes+ return self++ return Boxes(transformed_boxes, False)++ def transform_boxes_(self, M: torch.Tensor) -> "Boxes":+ """Inplace version of :func:`Boxes.transform_boxes`"""+ return self.transform_boxes(M, inplace=True)++ @property+ def _is_batch(self) -> bool:+ return self._boxes.ndim == 4++ @property+ def device(self) -> torch.device:+ """Returns boxes device."""+ return self._boxes.device++ @property+ def dtype(self) -> torch.dtype:+ """Returns boxes dtype."""+ return self._boxes.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)+ return self+++class Boxes3D:+ r"""3D boxes containing N or BxN boxes.++ Args:+ boxes: 3D boxes, shape of :math:`(N,8,3)` or :math:`(B,N,8,3)`. 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.++ Note:+ **3D boxes format** is defined as a floating data type tensor of shape ``Nx8x3`` or ``BxNx8x3`` where each box+ is a `hexahedron <https://en.wikipedia.org/wiki/Hexahedron>`_ defined by it's 8 vertices coordinates.+ Coordinates must be in ``x, y, z`` order. The height, width and depth of a box is defined as+ ``width = xmax - xmin + 1``, ``height = ymax - ymin + 1`` and ``depth = zmax - zmin + 1``. Examples of+ `hexahedrons <https://en.wikipedia.org/wiki/Hexahedron>`_ are cubes and rhombohedrons.+ """+ def __init__(self, boxes: torch.Tensor, raise_if_not_floating_point: bool = True):+ if not isinstance(boxes, torch.Tensor):+ raise TypeError(f"Input boxes is not a Tensor. Got: {type(boxes)}.")++ if not boxes.is_floating_point():+ if raise_if_not_floating_point:+ raise ValueError(f"Coordinates must be in floating point. Got {boxes.dtype}.")++ boxes = boxes.float()++ if len(boxes.shape) == 0:+ # Use reshape, so we don't end up creating a new tensor that does not depend on+ # the inputs (and consequently confuses jit)+ boxes = boxes.reshape((-1, 6))++ 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++ def get_boxes_shape(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ r"""Compute boxes heights and widths.++ Returns:+ - Boxes depths, shape of :math:`(N,)` or :math:`(B,N)`.+ - Boxes heights, shape of :math:`(N,)` or :math:`(B,N)`.+ - Boxes widths, shape of :math:`(N,)` or :math:`(B,N)`.++ Example:+ >>> boxes_xyzxyz = torch.tensor([[ 0, 1, 2, 10, 21, 32], [3, 4, 5, 43, 54, 65]])+ >>> boxes3d = Boxes3D.from_tensor(boxes_xyzxyz)+ >>> boxes3d.get_boxes_shape()+ (tensor([30., 60.]), tensor([20., 50.]), tensor([10., 40.]))+ """+ boxes_xyzwhd = self.to_tensor(mode='xyzwhd')+ widths, heights, depths = boxes_xyzwhd[..., 3], boxes_xyzwhd[..., 4], boxes_xyzwhd[..., 5]+ return depths, heights, widths++ @classmethod+ def from_tensor(cls, boxes: torch.Tensor, mode: str = "xyzxyz", validate_boxes: bool = True) -> "Boxes3D":+ r"""Helper method to easily create :class:`Boxes3D` from 3D boxes stored in another format.++ Args:+ boxes: 3D boxes, shape of :math:`(N,6)` or :math:`(B,N,6)`.+ mode: The format in which the 3D boxes are provided.++ * 'xyzxyz': boxes are assumed to be in the format ``xmin, ymin, zmin, xmax, ymax, zmax`` where+ ``width = xmax - xmin``, ``height = ymax - ymin`` and ``depth = zmax - zmin``.+ * 'xyzxyz_plus': similar to 'xyzxyz' mode but where box width, length and depth are defined as+ ``width = xmax - xmin + 1``, ``height = ymax - ymin + 1`` and ``depth = zmax - zmin + 1``.+ * 'xyzwhd': boxes are assumed to be in the format ``xmin, ymin, zmin, width, height, depth`` where+ ``width = xmax - xmin``, ``height = ymax - ymin`` and ``depth = zmax - zmin``.++ validate_boxes: check if boxes are valid rectangles or not. Valid rectangles are those with width, height+ and depth >= 1 (>= 2 when mode ends with '_plus' suffix).++ Returns:+ :class:`Boxes3D` class containing the original `boxes` in the format specified by ``mode``.++ 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)+ tensor([[[0., 3., 6.],+ [0., 3., 6.],+ [0., 3., 6.],+ [0., 3., 6.],+ [0., 3., 7.],+ [0., 3., 7.],+ [0., 3., 7.],+ [0., 3., 7.]],+ <BLANKLINE>+ [[5., 1., 3.],+ [7., 1., 3.],+ [7., 3., 3.],+ [5., 3., 3.],+ [5., 1., 8.],+ [7., 1., 8.],+ [7., 3., 8.],+ [5., 3., 8.]]])+ """+ if not (2 <= boxes.ndim <= 3 and boxes.shape[-1] == 6):+ raise ValueError(f"BBox shape must be (N, 6) or (B, N, 6). 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, zmin = boxes[..., 0], boxes[..., 1], boxes[..., 2]+ mode = mode.lower()+ if mode == "xyzxyz":+ width = boxes[..., 3] - boxes[..., 0]+ height = boxes[..., 4] - boxes[..., 1]+ depth = boxes[..., 5] - boxes[..., 2]+ elif mode == "xyzxyz_plus":+ width = boxes[..., 3] - boxes[..., 0] + 1+ height = boxes[..., 4] - boxes[..., 1] + 1+ depth = boxes[..., 5] - boxes[..., 2] + 1+ elif mode == "xyzwhd":+ depth, height, width = boxes[..., 4], boxes[..., 3], boxes[..., 5]+ 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.")+ if (depth <= 0).any():+ raise ValueError("Some boxes have negative depths or 0.")++ hexahedrons = _boxes3d_to_polygons3d(xmin, ymin, zmin, width, height, depth)+ hexahedrons = hexahedrons if batched else hexahedrons.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(hexahedrons, raise_if_not_floating_point=False)++ def to_tensor(self, mode: str = "xyzxyz") -> torch.Tensor:+ r"""Cast :class:`Boxes3D` to a tensor. ``mode`` controls which 3D boxes format should be use to represent boxes+ in the tensor.++ Args:+ mode: The format in which the boxes are provided.++ * 'xyzxyz': boxes are assumed to be in the format ``xmin, ymin, zmin, xmax, ymax, zmax`` where+ ``width = xmax - xmin``, ``height = ymax - ymin`` and ``depth = zmax - zmin``.+ * 'xyzxyz_plus': similar to 'xyzxyz' mode but where box width, length and depth are defined as+ ``width = xmax - xmin + 1``, ``height = ymax - ymin + 1`` and ``depth = zmax - zmin + 1``.+ * 'xyzwhd': boxes are assumed to be in the format ``xmin, ymin, zmin, width, height, depth`` where+ ``width = xmax - xmin``, ``height = ymax - ymin`` and ``depth = zmax - zmin``.+ * 'vertices': boxes are defined by their vertices points in the following ``clockwise`` order:+ *front-top-left, front-top-right, front-bottom-right, front-bottom-left, back-top-left,+ back-top-right, back-bottom-right, back-bottom-left*. Vertices coordinates are in (x,y, z) order.+ Finally, box width, height and depth are defined as ``width = xmax - xmin``, ``height = ymax - ymin``+ and ``depth = zmax - zmin``.+ * 'vertices_plus': similar to 'vertices' mode but where box width, length and depth are defined as+ ``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``.++ Returns:+ 3D Boxes tensor in the ``mode`` format. The shape depends with the ``mode`` value:++ * 'vertices' or 'verticies_plus': :math:`(N, 8, 3)` or :math:`(B, N, 8, 3)`.+ * Any other value: :math:`(N, 6)` or :math:`(B, N, 6)`.++ Note:+ It is currently non-differentiable due to a bug. See github issue+ `#1304 <https://github.com/kornia/kornia/issues/1396>`_.++ 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')+ >>> assert (boxes.to_tensor(mode='xyzxyz') == boxes_xyzxyz).all()+ """+ if self._boxes.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)++ # Create boxes in xyzxyz_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], 6+ )++ mode = mode.lower()+ if mode in ("xyzxyz", "xyzxyz_plus"):+ pass+ elif mode in ("xyzwhd", "vertices", "vertices_plus"):+ width = boxes[..., 3] - boxes[..., 0] + 1+ height = boxes[..., 4] - boxes[..., 1] + 1+ depth = boxes[..., 5] - boxes[..., 2] + 1+ boxes[..., 3] = width+ boxes[..., 4] = height+ boxes[..., 5] = depth+ else:+ raise ValueError(f"Unknown mode {mode}")++ if mode in ("xyzxyz", "vertices"):+ offset = torch.as_tensor([0, 0, 0, 1, 1, 1], device=boxes.device, dtype=boxes.dtype)+ boxes = boxes + offset++ if mode.startswith('vertices'):+ xmin, ymin, zmin = boxes[..., 0], boxes[..., 1], boxes[..., 2]+ width, height, depth = boxes[..., 3], boxes[..., 4], boxes[..., 5]++ boxes = _boxes3d_to_polygons3d(xmin, ymin, zmin, width, height, depth)++ boxes = boxes if self._is_batch else boxes.squeeze(0)+ return boxes++ def to_mask(self, depth: int, height: int, width: int) -> torch.Tensor:+ """Convert Β·D boxes to masks. Covered area is 1 and the remaining is 0.++ Args:+ depth: depth of the masked image/images.+ height: height of the masked image/images.+ width: width of the masked image/images.++ Returns:+ the output mask tensor, shape of :math:`(N, depth, width, height)` or :math:`(B,N, depth, width, height)`+ and dtype of :func:`Boxes3D.dtype` (it can be any floating point dtype).++ Note:+ It is currently non-differentiable.++ Examples:+ >>> boxes = Boxes3D(torch.tensor([[ # Equivalent to boxes = Boxes.3Dfrom_tensor([[1,1,1,3,3,2]])+ ... [1., 1., 1.],+ ... [3., 1., 1.],+ ... [3., 3., 1.],+ ... [1., 3., 1.],+ ... [1., 1., 2.],+ ... [3., 1., 2.],+ ... [3., 3., 2.],+ ... [1., 3., 2.],+ ... ]])) # 1x8x3+ >>> boxes.to_mask(4, 5, 5)+ tensor([[[[0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.]],+ <BLANKLINE>+ [[0., 0., 0., 0., 0.],+ [0., 1., 1., 1., 0.],+ [0., 1., 1., 1., 0.],+ [0., 1., 1., 1., 0.],+ [0., 0., 0., 0., 0.]],+ <BLANKLINE>+ [[0., 0., 0., 0., 0.],+ [0., 1., 1., 1., 0.],+ [0., 1., 1., 1., 0.],+ [0., 1., 1., 1., 0.],+ [0., 0., 0., 0., 0.]],+ <BLANKLINE>+ [[0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.],+ [0., 0., 0., 0., 0.]]]])+ """+ if self._boxes.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)+ mask = torch.zeros(+ (self._boxes.shape[0], self._boxes.shape[1], depth, height, width),+ dtype=self._boxes.dtype,+ device=self._boxes.device,+ )+ else: # (N, 8, 3)+ mask = torch.zeros(+ (self._boxes.shape[0], depth, height, width), dtype=self._boxes.dtype, device=self._boxes.device+ )++ # Boxes coordinates can be outside the image size after transforms. Clamp values to the image size+ clipped_boxes_xyzxyz = self.to_tensor("xyzxyz")+ clipped_boxes_xyzxyz[..., ::3].clamp_(0, width)+ clipped_boxes_xyzxyz[..., 1::3].clamp_(0, height)+ clipped_boxes_xyzxyz[..., 2::3].clamp_(0, depth)++ # Reshape mask to (BxN, D, H, W) and boxes to (BxN, 6) to iterate over all of them.+ # Cast boxes coordinates to be integer to use them as indexes. Use round to handle decimal values.+ for mask_channel, box_xyzxyz in zip(+ mask.view(-1, depth, height, width), clipped_boxes_xyzxyz.view(-1, 6).round().int()+ ):+ # Mask channel dimensions: (depth, height, width)+ mask_channel[+ box_xyzxyz[2] : box_xyzxyz[5], box_xyzxyz[1] : box_xyzxyz[4], box_xyzxyz[0] : box_xyzxyz[3]+ ] = 1++ return mask++ def transform_boxes(self, M: torch.Tensor, inplace: bool = False) -> "Boxes3D":+ r"""Apply a transformation matrix to the 3D boxes.++ Args:+ M: The transformation matrix to be applied, shape of :math:`(4, 4)` or :math:`(B, 4, 4)`.+ inplace: do transform in-place and return self.++ Returns:+ The transformed boxes.+ """+ if not 2 <= M.ndim <= 3 or M.shape[-2:] != (4, 4):+ raise ValueError(f"The transformation matrix shape must be (4, 4) or (B, 4, 4). Got {M.shape}.")++ # 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)+ if inplace:+ self._boxes = transformed_boxes+ return self++ return Boxes3D(transformed_boxes, False)++ def transform_boxes_(self, M: torch.Tensor) -> "Boxes3D":+ """Inplace version of :func:`Boxes3D.transform_boxes`"""+ return self.transform_boxes(M, inplace=True)++ @property+ def _is_batch(self) -> bool:+ return self._boxes.ndim == 4++ @property+ def device(self) -> torch.device:+ """Returns boxes device."""+ return self._boxes.device++ @property+ def dtype(self) -> torch.dtype:+ """Returns boxes dtype."""+ return self._boxes.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)+ return selfdiff --git a/test/geometry/test_boxes.py b/test/geometry/test_boxes.pynew file mode 100644index 000000000..8dc18a8e9--- /dev/null+++ b/test/geometry/test_boxes.py@@ -0,0 +1,864 @@+from functools import partial+from typing import Tuple++import pytest+import torch+from torch.autograd import gradcheck+from torch.testing import assert_allclose++import kornia.testing as utils+from kornia.geometry.boxes import Boxes, Boxes3D+++class TestBoxes2D:+ def test_smoke(self, device, dtype):+ def _create_tensor_box():+ # Sample two points of the rectangle+ points = torch.rand(1, 4, device=device, dtype=dtype)++ # Fill according missing points+ tensor_boxes = torch.zeros(1, 4, 2, device=device, dtype=dtype)+ tensor_boxes[0, 0] = points[0][:2]+ tensor_boxes[0, 1, 0] = points[0][2]+ tensor_boxes[0, 1, 1] = points[0][1]+ tensor_boxes[0, 2] = points[0][2:]+ tensor_boxes[0, 3, 0] = points[0][0]+ tensor_boxes[0, 3, 1] = points[0][3]+ return tensor_boxes++ # Validate+ assert Boxes(_create_tensor_box()) # Validate 1 box++ # 2 boxes without batching (N, 4, 2) where N=2+ two_boxes = torch.cat([_create_tensor_box(), _create_tensor_box()])+ assert Boxes(two_boxes)++ # 2 boxes in batch (B, 1, 4, 2) where B=2+ batched_bbox = torch.stack([_create_tensor_box(), _create_tensor_box()])+ assert Boxes(batched_bbox)++ def test_get_boxes_shape(self, device, dtype):+ box = Boxes(torch.tensor([[[1.0, 1.0], [3.0, 2.0], [1.0, 2.0], [3.0, 1.0]]], device=device, dtype=dtype))+ t_boxes = torch.tensor(+ [[[1.0, 1.0], [3.0, 1.0], [1.0, 2.0], [3.0, 2.0]], [[5.0, 4.0], [2.0, 2.0], [5.0, 2.0], [2.0, 4.0]]],+ device=device,+ dtype=dtype,+ ) # (2, 4, 2)+ boxes = Boxes(t_boxes)+ boxes_batch = Boxes(t_boxes[None]) # (1, 2, 4, 2)++ # Single box+ h, w = box.get_boxes_shape()+ assert (h.item(), w.item()) == (2, 3)++ # Boxes+ h, w = boxes.get_boxes_shape()+ assert h.ndim == 1 and w.ndim == 1+ assert len(h) == 2 and len(w) == 2+ assert (h == torch.as_tensor([2.0, 3.0], device=device)).all() and (+ w == torch.as_tensor([3.0, 4.0], device=device)+ ).all()++ # Box batch+ h, w = boxes_batch.get_boxes_shape()+ assert h.ndim == 2 and w.ndim == 2+ assert h.shape == (1, 2) and w.shape == (1, 2)+ assert (h == torch.as_tensor([[2.0, 3.0]], device=device)).all() and (+ w == torch.as_tensor([[3.0, 4.0]], device=device)+ ).all()++ def test_get_boxes_shape_batch(self, device, dtype):+ t_box1 = torch.tensor([[[1.0, 1.0], [3.0, 2.0], [3.0, 1.0], [1.0, 2.0]]], device=device, dtype=dtype)+ t_box2 = torch.tensor([[[5.0, 2.0], [2.0, 2.0], [5.0, 4.0], [2.0, 4.0]]], device=device, dtype=dtype)+ batched_boxes = Boxes(torch.stack([t_box1, t_box2]))++ h, w = batched_boxes.get_boxes_shape()+ assert h.ndim == 2 and w.ndim == 2+ assert h.shape == (2, 1) and w.shape == (2, 1)+ assert (h == torch.as_tensor([[2], [3]], device=device)).all() and (+ w == torch.as_tensor([[3], [4]], device=device)+ ).all()++ @pytest.mark.parametrize('shape', [(1, 4), (1, 1, 4)])+ def test_from_tensor(self, shape: Tuple[int], device, dtype):+ box_xyxy = torch.as_tensor([[1, 2, 3, 4]], device=device, dtype=dtype).view(*shape)+ box_xyxy_plus = torch.as_tensor([[1, 2, 2, 3]], device=device, dtype=dtype).view(*shape)+ box_xywh = torch.as_tensor([[1, 2, 2, 2]], device=device, dtype=dtype).view(*shape)++ 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++ assert boxes_xyxy.shape == expected_box.shape+ assert_allclose(boxes_xyxy, expected_box)++ assert boxes_xyxy_plus.shape == expected_box.shape+ assert_allclose(boxes_xyxy_plus, expected_box)++ assert boxes_xywh.shape == expected_box.shape+ assert_allclose(boxes_xywh, expected_box)++ @pytest.mark.parametrize('shape', [(1, 4), (1, 1, 4)])+ def test_from_invalid_tensor(self, shape: Tuple[int], device, dtype):+ box_xyxy = torch.as_tensor([[1, 2, -3, 4]], device=device, dtype=dtype).view(*shape) # Invalid width+ box_xyxy_plus = torch.as_tensor([[1, 2, 0, 3]], device=device, dtype=dtype).view(*shape) # Invalid height++ try:+ Boxes.from_tensor(box_xyxy, mode='xyxy')+ assert False, "Boxes.from_tensor should have raised any exception"+ except ValueError:+ pass++ try:+ Boxes.from_tensor(box_xyxy_plus, mode='xyxy_plus')+ assert False, "Boxes.from_tensor should have raised any exception"+ except ValueError:+ pass++ @pytest.mark.parametrize('shape', [(1, 4), (1, 1, 4)])+ def test_boxes_to_tensor(self, shape: Tuple[int], device, dtype):+ # quadrilateral with randomized vertices to reflect possible transforms.+ box = Boxes(torch.as_tensor([[[2, 2], [2, 3], [1, 3], [1, 2]]], device=device, dtype=dtype).view(*shape, 2))++ expected_box_xyxy = torch.as_tensor([[1, 2, 3, 4]], device=device, dtype=dtype).view(*shape)+ expected_box_xyxy_plus = torch.as_tensor([[1, 2, 2, 3]], device=device, dtype=dtype).view(*shape)+ expected_box_xywh = torch.as_tensor([[1, 2, 2, 2]], device=device, dtype=dtype).view(*shape)+ expected_vertices = torch.as_tensor([[[1, 2], [3, 2], [3, 4], [1, 4]]], device=device, dtype=dtype).view(+ *shape, 2+ )+ expected_vertices_plus = torch.as_tensor([[[1, 2], [2, 2], [2, 3], [1, 3]]], device=device, dtype=dtype).view(+ *shape, 2+ )++ boxes_xyxy = box.to_tensor(mode='xyxy')+ boxes_xyxy_plus = box.to_tensor(mode='xyxy_plus')+ boxes_xywh = box.to_tensor(mode='xywh')+ 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_allclose(boxes_xyxy, expected_box_xyxy)++ assert boxes_xyxy_plus.shape == expected_box_xyxy_plus.shape+ assert_allclose(boxes_xyxy_plus, expected_box_xyxy_plus)++ assert boxes_xywh.shape == expected_box_xywh.shape+ assert_allclose(boxes_xywh, expected_box_xywh)++ assert boxes_vertices.shape == expected_vertices.shape+ assert_allclose(boxes_vertices, expected_vertices)++ assert boxes_vertices_plus.shape == expected_vertices_plus.shape+ assert_allclose(boxes_vertices_plus, expected_vertices_plus)++ 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+ ) # (1, 4, 2)+ t_box2 = torch.tensor(+ [[[2.0, 2.0], [4.0, 2.0], [4.0, 5.0], [2.0, 4.0]]], device=device, dtype=dtype+ ) # (1, 4, 2)+ box1, box2 = Boxes(t_box1), Boxes(t_box2)+ two_boxes = Boxes(torch.cat([t_box1, t_box2])) # (2, 4, 2)+ batched_boxes = Boxes(torch.stack([t_box1, t_box2])) # (2, 1, 4, 2)++ height, width = 7, 5++ expected_mask1 = torch.tensor(+ [+ [+ [0, 0, 0, 0, 0],+ [0, 1, 1, 1, 0],+ [0, 1, 1, 1, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ ]+ ],+ device=device,+ dtype=dtype,+ )++ expected_mask2 = torch.tensor(+ [+ [+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 1, 1, 1],+ [0, 0, 1, 1, 1],+ [0, 0, 1, 1, 1],+ [0, 0, 1, 1, 1],+ [0, 0, 0, 0, 0],+ ]+ ],+ device=device,+ dtype=dtype,+ )+ expected_two_masks = torch.cat([expected_mask1, expected_mask2])+ expected_batched_masks = torch.stack([expected_mask1, expected_mask2])++ mask1 = box1.to_mask(height, width)+ mask2 = box2.to_mask(height, width)+ two_masks = two_boxes.to_mask(height, width)+ batched_masks = batched_boxes.to_mask(height, width)++ assert mask1.shape == expected_mask1.shape+ assert_allclose(mask1, expected_mask1)++ assert mask2.shape == expected_mask2.shape+ assert_allclose(mask2, expected_mask2)++ assert two_masks.shape == expected_two_masks.shape+ assert_allclose(two_masks, expected_two_masks)++ assert batched_masks.shape == expected_batched_masks.shape+ assert_allclose(batched_masks, expected_batched_masks)++ 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++ 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++ 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++ t_boxes1 = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)++ t_boxes1 = utils.tensor_to_gradcheck_var(t_boxes1)+ t_boxes2 = utils.tensor_to_gradcheck_var(t_boxes1.detach().clone())+ t_boxes3 = utils.tensor_to_gradcheck_var(t_boxes1.detach().clone())+ t_boxes4 = utils.tensor_to_gradcheck_var(t_boxes1.detach().clone())+ t_boxes_xyxy = utils.tensor_to_gradcheck_var(torch.tensor([[1.0, 3.0, 5.0, 6.0]]))+ t_boxes_xyxy1 = utils.tensor_to_gradcheck_var(t_boxes_xyxy.detach().clone())++ assert gradcheck(partial(apply_boxes_method, method='to_tensor'), (t_boxes2,), raise_exception=True)+ assert gradcheck(+ partial(apply_boxes_method, method='to_tensor', mode='xyxy_plus'), (t_boxes3,), raise_exception=True+ )+ assert gradcheck(+ partial(apply_boxes_method, method='to_tensor', mode='vertices_plus'), (t_boxes4,), raise_exception=True+ )+ 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+ )+ assert gradcheck(+ lambda x: Boxes.from_tensor(x, mode='xywh')._boxes, (t_boxes_xyxy1,), raise_exception=True+ )+++class TestTransformBoxes2D:+ def test_transform_boxes(self, device, dtype):+ # Define boxes in XYXY format for simplicity.+ boxes_xyxy = torch.tensor([[139.2640, 103.0150, 398.3120, 411.5225]], device=device, dtype=dtype)+ expected_boxes_xyxy = torch.tensor([[372.7360, 103.0150, 115.6880, 411.5225]], device=device, dtype=dtype)++ boxes = Boxes.from_tensor(boxes_xyxy)+ expected_boxes = Boxes.from_tensor(expected_boxes_xyxy, validate_boxes=False)++ 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)+ # inplace check+ assert transformed_boxes is not boxes++ def test_transform_boxes_(self, device, dtype):+ # Define boxes in XYXY format for simplicity.+ boxes_xyxy = torch.tensor([[139.2640, 103.0150, 398.3120, 411.5225]], device=device, dtype=dtype)+ expected_boxes_xyxy = torch.tensor([[372.7360, 103.0150, 115.6880, 411.5225]], device=device, dtype=dtype)++ boxes = Boxes.from_tensor(boxes_xyxy)+ expected_boxes = Boxes.from_tensor(expected_boxes_xyxy, validate_boxes=False)++ 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)+ # inplace check+ assert transformed_boxes is boxes++ def test_transform_multiple_boxes(self, device, dtype):+ # Define boxes in XYXY format for simplicity.+ boxes_xyxy = torch.tensor(+ [+ [139.2640, 103.0150, 398.3120, 411.5225],+ [1.0240, 80.5547, 513.0000, 513.0000],+ [165.2053, 262.1440, 511.6347, 509.9280],+ [119.8080, 144.2067, 258.0240, 411.1292],+ ],+ device=device,+ dtype=dtype,+ ).repeat(+ 2, 1, 1+ ) # 2 x 4 x 4 two images 4 boxes each++ expected_boxes_xyxy = torch.tensor(+ [+ [+ [372.7360, 103.0150, 115.6880, 411.5225],+ [510.9760, 80.5547, 1.0000, 513.0000],+ [346.7947, 262.1440, 2.3653, 509.9280],+ [392.1920, 144.2067, 255.9760, 411.1292],+ ],+ [+ [139.2640, 103.0150, 398.3120, 411.5225],+ [1.0240, 80.5547, 513.0000, 513.0000],+ [165.2053, 262.1440, 511.6347, 509.9280],+ [119.8080, 144.2067, 258.0240, 411.1292],+ ],+ ],+ device=device,+ dtype=dtype,+ )++ trans_mat = torch.tensor(+ [+ [[-1.0, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],+ [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],+ ],+ device=device,+ dtype=dtype,+ )++ boxes = Boxes.from_tensor(boxes_xyxy)+ 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)++ def test_gradcheck(self, device, dtype):+ # Define boxes in XYXY format for simplicity.+ boxes_xyxy = torch.tensor(+ [+ [139.2640, 103.0150, 258.0480, 307.5075],+ [1.0240, 80.5547, 510.9760, 431.4453],+ [165.2053, 262.1440, 345.4293, 546.7840],+ [119.8080, 144.2067, 137.2160, 265.9225],+ ],+ device=device,+ dtype=dtype,+ )+ boxes = Boxes.from_tensor(boxes_xyxy)++ 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)++ def _wrapper_transform_boxes(quadrilaterals, M):+ boxes = Boxes(quadrilaterals)+ boxes = boxes.transform_boxes(M)+ return boxes._boxes++ assert gradcheck(_wrapper_transform_boxes, (t_boxes, trans_mat), raise_exception=True)+++class TestBbox3D:+ def test_smoke(self, device, dtype):+ def _create_tensor_box():+ # Sample two points of the 3d rect+ points = torch.rand(1, 6, device=device, dtype=dtype)++ # Fill according missing points+ tensor_boxes = torch.zeros(1, 8, 3, device=device, dtype=dtype)+ tensor_boxes[0, 0] = points[0][:3]+ tensor_boxes[0, 1, 0] = points[0][3]+ tensor_boxes[0, 1, 1] = points[0][1]+ tensor_boxes[0, 1, 2] = points[0][2]+ tensor_boxes[0, 2, 0] = points[0][3]+ tensor_boxes[0, 2, 1] = points[0][4]+ tensor_boxes[0, 2, 2] = points[0][2]+ tensor_boxes[0, 3, 0] = points[0][0]+ tensor_boxes[0, 3, 1] = points[0][4]+ tensor_boxes[0, 3, 2] = points[0][2]+ tensor_boxes[0, 4, 0] = points[0][0]+ tensor_boxes[0, 4, 1] = points[0][1]+ tensor_boxes[0, 4, 2] = points[0][5]+ tensor_boxes[0, 5, 0] = points[0][3]+ tensor_boxes[0, 5, 1] = points[0][1]+ tensor_boxes[0, 5, 2] = points[0][5]+ tensor_boxes[0, 6] = points[0][3:]+ tensor_boxes[0, 7, 0] = points[0][0]+ tensor_boxes[0, 7, 1] = points[0][4]+ tensor_boxes[0, 7, 2] = points[0][5]+ return tensor_boxes++ # Validate+ assert Boxes3D(_create_tensor_box()) # Validate 1 box++ # 2 boxes without batching (N, 8, 3) where N=2+ two_boxes = torch.cat([_create_tensor_box(), _create_tensor_box()])+ assert Boxes3D(two_boxes)++ # 2 boxes in batch (B, 1, 8, 3) where B=2+ batched_bbox = torch.stack([_create_tensor_box(), _create_tensor_box()])+ assert Boxes3D(batched_bbox)++ def test_get_boxes_shape(self, device, dtype):+ box = Boxes3D(+ torch.tensor(+ [[[0, 1, 2], [0, 1, 32], [10, 21, 2], [0, 21, 2], [10, 1, 32], [10, 21, 32], [10, 1, 2], [0, 21, 32]]],+ device=device,+ dtype=dtype,+ )+ ) # 1x8x3+ t_boxes = torch.tensor(+ [+ [[0, 21, 32], [0, 1, 2], [10, 1, 2], [0, 21, 2], [0, 1, 32], [10, 21, 2], [10, 1, 32], [10, 21, 32]],+ [[3, 4, 5], [3, 4, 65], [43, 54, 5], [3, 54, 5], [43, 4, 5], [43, 4, 65], [43, 54, 65], [3, 54, 65]],+ ],+ device=device,+ dtype=dtype,+ ) # 2x8x3+ boxes = Boxes3D(t_boxes)+ boxes_batch = Boxes3D(t_boxes[None]) # (1, 2, 8, 3)++ # Single box+ d, h, w = box.get_boxes_shape()+ assert (d.item(), h.item(), w.item()) == (31.0, 21.0, 11.0)++ # Boxes+ d, h, w = boxes.get_boxes_shape()+ assert h.ndim == 1 and w.ndim == 1+ assert len(d) == 2 and len(h) == 2 and len(w) == 2+ assert (+ (d == torch.as_tensor([31.0, 61.0], device=device)).all()+ and (h == torch.as_tensor([21.0, 51.0], device=device)).all()+ and (w == torch.as_tensor([11.0, 41.0], device=device)).all()+ )++ # Box batch+ d, h, w = boxes_batch.get_boxes_shape()+ assert h.ndim == 2 and w.ndim == 2+ assert h.shape == (1, 2) and w.shape == (1, 2)+ assert (+ (d == torch.as_tensor([[31.0, 61.0]], device=device)).all()+ and (h == torch.as_tensor([[21.0, 51.0]], device=device)).all()+ and (w == torch.as_tensor([[11.0, 41.0]], device=device)).all()+ )++ def test_get_boxes_shape_batch(self, device, dtype):+ t_box1 = torch.tensor(+ [[[0, 1, 2], [0, 1, 32], [10, 21, 2], [0, 21, 2], [10, 1, 32], [10, 21, 32], [10, 1, 2], [0, 21, 32]]],+ device=device,+ dtype=dtype+ )+ t_box2 = torch.tensor(+ [[[3, 4, 5], [3, 4, 65], [43, 54, 5], [3, 54, 5], [43, 4, 5], [43, 4, 65], [43, 54, 65], [3, 54, 65]]],+ device=device,+ dtype=dtype+ )+ batched_boxes = Boxes3D(torch.stack([t_box1, t_box2]))++ d, h, w = batched_boxes.get_boxes_shape()+ assert d.ndim == 2 and h.ndim == 2 and w.ndim == 2+ assert d.shape == (2, 1) and h.shape == (2, 1) and w.shape == (2, 1)+ assert (+ (d == torch.as_tensor([[31.0], [61.0]], device=device)).all()+ and (h == torch.as_tensor([[21.0], [51.0]], device=device)).all()+ and (w == torch.as_tensor([[11.0], [41.0]], device=device)).all()+ )++ @pytest.mark.parametrize('shape', [(1, 6), (1, 1, 6)])+ def test_from_tensor(self, shape: Tuple[int], device, dtype):+ box_xyzxyz = torch.as_tensor([[1, 2, 3, 4, 5, 6]], device=device, dtype=dtype).view(*shape)+ box_xyzxyz_plus = torch.as_tensor([[1, 2, 3, 3, 4, 5]], device=device, dtype=dtype).view(*shape)+ box_xyzwhd = torch.as_tensor([[1, 2, 3, 3, 3, 3]], device=device, dtype=dtype).view(*shape)++ expected_box = torch.as_tensor(+ [[[1, 2, 3], [3, 2, 3], [3, 4, 3], [1, 4, 3], [1, 2, 5], [3, 2, 5], [3, 4, 5], [1, 4, 5]]], # Front # Back+ device=device,+ 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++ assert kornia_xyzxyz.shape == expected_box.shape+ assert_allclose(kornia_xyzxyz, expected_box)++ assert kornia_xyzxyz_plus.shape == expected_box.shape+ assert_allclose(kornia_xyzxyz_plus, expected_box)++ assert kornia_xyzwhd.shape == expected_box.shape+ assert_allclose(kornia_xyzwhd, expected_box)++ @pytest.mark.parametrize('shape', [(1, 6), (1, 1, 6)])+ def test_from_invalid_tensor(self, shape: Tuple[int], device, dtype):+ box_xyzxyz = torch.as_tensor([[1, 2, 3, 4, -5, 6]], device=device, dtype=dtype).view(*shape)+ box_xyzxyz_plus = torch.as_tensor([[1, 2, 3, 0, 6, 4]], device=device, dtype=dtype).view(*shape)++ try:+ Boxes3D.from_tensor(box_xyzxyz, mode='xyzxyz')+ assert False, "Boxes3D.from_tensor should have raised any exception"+ except ValueError:+ pass++ try:+ Boxes3D.from_tensor(box_xyzxyz_plus, mode='xyzxyz_plus')+ assert False, "Boxes3D.from_tensor should have raised any exception"+ except ValueError:+ pass++ @pytest.mark.parametrize('shape', [(1, 6), (1, 1, 6)])+ def test_boxes_to_tensor(self, shape: Tuple[int], device, dtype):+ # Hexahedron with randomized vertices to reflect possible transforms.+ box = Boxes3D(+ torch.as_tensor(+ [[[2, 2, 1], [1, 2, 1], [2, 3, 2], [1, 3, 2], [2, 2, 2], [1, 3, 1], [2, 3, 1], [1, 2, 2]]],+ device=device,+ dtype=dtype,+ ).view(*shape[:-1], 8, 3)+ )++ expected_box_xyzxyz = torch.as_tensor([[1, 2, 1, 3, 4, 3]], device=device, dtype=dtype).view(*shape)+ expected_box_xyzxyz_plus = torch.as_tensor([[1, 2, 1, 2, 3, 2]], device=device, dtype=dtype).view(*shape)+ expected_box_xyzwhd = torch.as_tensor([[1, 2, 1, 2, 2, 2]], device=device, dtype=dtype).view(*shape)+ expected_vertices = torch.as_tensor(+ [[[1, 2, 1], [3, 2, 1], [3, 4, 1], [1, 4, 1], [1, 2, 3], [3, 2, 3], [3, 4, 3], [1, 4, 3]]], # Front # Back+ device=device,+ dtype=dtype,+ ).view(*shape[:-1], 8, 3)+ expected_vertices_plus = torch.as_tensor(+ [[[1, 2, 1], [2, 2, 1], [2, 3, 1], [1, 3, 1], [1, 2, 2], [2, 2, 2], [2, 3, 2], [1, 3, 2]]], # Front # Back+ device=device,+ dtype=dtype,+ ).view(*shape[:-1], 8, 3)++ kornia_xyzxyz = box.to_tensor(mode='xyzxyz')+ kornia_xyzxyz_plus = box.to_tensor(mode='xyzxyz_plus')+ kornia_xyzwhd = box.to_tensor(mode='xyzwhd')+ kornia_vertices = box.to_tensor(mode='vertices')+ kornia_vertices_plus = box.to_tensor(mode='vertices_plus')++ assert kornia_xyzxyz.shape == expected_box_xyzxyz.shape+ assert_allclose(kornia_xyzxyz, expected_box_xyzxyz)++ assert kornia_xyzxyz_plus.shape == expected_box_xyzxyz_plus.shape+ assert_allclose(kornia_xyzxyz_plus, expected_box_xyzxyz_plus)++ assert kornia_xyzwhd.shape == expected_box_xyzwhd.shape+ assert_allclose(kornia_xyzwhd, expected_box_xyzwhd)++ assert kornia_vertices.shape == expected_vertices.shape+ assert_allclose(kornia_vertices, expected_vertices)++ assert kornia_vertices_plus.shape == expected_vertices_plus.shape+ assert_allclose(kornia_vertices_plus, expected_vertices_plus)++ def test_bbox_to_mask(self, device, dtype):+ t_box1 = torch.tensor(+ [+ [+ [1.0, 1.0, 1.0],+ [3.0, 1.0, 1.0],+ [3.0, 2.0, 1.0],+ [1.0, 2.0, 1.0], # Front+ [1.0, 1.0, 2.0],+ [3.0, 1.0, 2.0],+ [3.0, 2.0, 2.0],+ [1.0, 2.0, 2.0], # Back+ ]+ ],+ device=device,+ dtype=dtype,+ ) # (1, 8, 3)+ t_box2 = torch.tensor(+ [+ [+ [2.0, 2.0, 1.0],+ [4.0, 2.0, 1.0],+ [4.0, 5.0, 1.0],+ [4.0, 2.0, 1.0], # Front+ [2.0, 2.0, 1.0],+ [4.0, 2.0, 1.0],+ [4.0, 5.0, 1.0],+ [4.0, 5.0, 1.0], # Back+ ]+ ],+ device=device,+ dtype=dtype,+ ) # (1, 8, 3)++ box1, box2 = Boxes3D(t_box1), Boxes3D(t_box2)+ two_boxes = Boxes3D(torch.cat([t_box1, t_box2])) # (2, 8, 3)+ batched_boxes = Boxes3D(torch.stack([t_box1, t_box2])) # (2, 1, 8, 3)++ depth, height, width = 3, 7, 5++ expected_mask1 = torch.tensor(+ [+ [+ [ # Depth 0+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ ],+ [ # Depth 1+ [0, 0, 0, 0, 0],+ [0, 1, 1, 1, 0],+ [0, 1, 1, 1, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ ],+ [ # Depth 2+ [0, 0, 0, 0, 0],+ [0, 1, 1, 1, 0],+ [0, 1, 1, 1, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ ],+ ]+ ],+ device=device,+ dtype=dtype,+ )++ expected_mask2 = torch.tensor(+ [+ [+ [ # Depth 0+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ ],+ [ # Depth 1+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 1, 1, 1],+ [0, 0, 1, 1, 1],+ [0, 0, 1, 1, 1],+ [0, 0, 1, 1, 1],+ [0, 0, 0, 0, 0],+ ],+ [ # Depth 2+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ [0, 0, 0, 0, 0],+ ],+ ]+ ],+ device=device,+ dtype=dtype,+ )+ expected_two_masks = torch.cat([expected_mask1, expected_mask2])+ expected_batched_masks = torch.stack([expected_mask1, expected_mask2])++ mask1 = box1.to_mask(depth, height, width)+ mask2 = box2.to_mask(depth, height, width)+ two_masks = two_boxes.to_mask(depth, height, width)+ batched_masks = batched_boxes.to_mask(depth, height, width)++ assert mask1.shape == expected_mask1.shape+ assert_allclose(mask1, expected_mask1)++ assert mask2.shape == expected_mask2.shape+ assert_allclose(mask2, expected_mask2)++ assert two_masks.shape == expected_two_masks.shape+ assert_allclose(two_masks, expected_two_masks)++ assert batched_masks.shape == expected_batched_masks.shape+ assert_allclose(batched_masks, expected_batched_masks)++ 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++ 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++ 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++ 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]]],+ device=device,+ dtype=dtype,+ )++ t_boxes1 = utils.tensor_to_gradcheck_var(t_boxes1)+ # Uncomment when enabling gradient checks+ # t_boxes2 = utils.tensor_to_gradcheck_var(t_boxes1.detach().clone())+ # t_boxes3 = utils.tensor_to_gradcheck_var(t_boxes1.detach().clone())+ # t_boxes4 = utils.tensor_to_gradcheck_var(t_boxes1.detach().clone())+ t_boxes_xyzxyz = utils.tensor_to_gradcheck_var(torch.tensor([[1.0, 3.0, 8.0, 5.0, 6.0, 12.0]]))+ t_boxes_xyzxyz1 = utils.tensor_to_gradcheck_var(t_boxes_xyzxyz.detach().clone())++ # Gradient checks for Boxes3D.to_tensor (and Boxes3D.get_boxes_shape) are disable since the is a bug+ # in their gradient. See https://github.com/kornia/kornia/issues/1396.+ # assert gradcheck(partial(apply_boxes_method, method='to_tensor'), (t_boxes2,), raise_exception=True)+ # assert gradcheck(+ # partial(apply_boxes_method, method='to_tensor', mode='xyzxyz_plus'), (t_boxes3,), raise_exception=True+ # )+ # assert gradcheck(+ # partial(apply_boxes_method, method='to_tensor', mode='vertices_plus'), (t_boxes4,), raise_exception=True+ # )+ # 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+ )+ assert gradcheck(+ lambda x: Boxes3D.from_tensor(x, mode='xyzwhd')._boxes, (t_boxes_xyzxyz1,), raise_exception=True+ )+++class TestTransformBoxes3D:+ def test_transform_boxes(self, device, dtype):+ # Define boxes in XYZXYZ format for simplicity.+ boxes_xyzxyz = torch.tensor(+ [[139.2640, 103.0150, 283.162, 398.3120, 411.5225, 454.185]], device=device, dtype=dtype+ )+ expected_boxes_xyzxyz = torch.tensor(+ [[372.7360, 103.0150, 567.324, 115.6880, 411.5225, 908.37]], device=device, dtype=dtype+ )++ boxes = Boxes3D.from_tensor(boxes_xyzxyz)+ expected_boxes = Boxes3D.from_tensor(expected_boxes_xyzxyz, validate_boxes=False)++ trans_mat = torch.tensor(+ [[[-1.0, 0.0, 0.0, 512.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 2.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)+ # inplace check+ assert transformed_boxes is not boxes++ def test_transform_boxes_(self, device, dtype):+ # Define boxes in XYZXYZ format for simplicity.+ boxes_xyzxyz = torch.tensor(+ [[139.2640, 103.0150, 283.162, 398.3120, 411.5225, 454.185]], device=device, dtype=dtype+ )+ expected_boxes_xyzxyz = torch.tensor(+ [[372.7360, 103.0150, 567.324, 115.6880, 411.5225, 908.37]], device=device, dtype=dtype+ )++ boxes = Boxes3D.from_tensor(boxes_xyzxyz)+ expected_boxes = Boxes3D.from_tensor(expected_boxes_xyzxyz, validate_boxes=False)++ trans_mat = torch.tensor(+ [[[-1.0, 0.0, 0.0, 512.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 2.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)+ # inplace check+ assert transformed_boxes is boxes++ def test_transform_multiple_boxes(self, device, dtype):+ # Define boxes in XYZXYZ format for simplicity.+ boxes_xyzxyz = torch.tensor(+ [+ [139.2640, 103.0150, 283.162, 398.3120, 411.5225, 454.185],+ [1.0240, 80.5547, 469.50, 513.0000, 513.0000, 513.0],+ [165.2053, 262.1440, 42.98, 511.6347, 509.9280, 785.443],+ [119.8080, 144.2067, 234.21, 258.0240, 411.1292, 387.14],+ ],+ device=device,+ dtype=dtype,+ ).repeat(+ 2, 1, 1+ ) # 2 x 4 x 4 two images 4 boxes each++ expected_boxes_xyzxyz = torch.tensor(+ [+ [+ [372.7360, 103.0150, 567.324, 115.6880, 411.5225, 908.37],+ [510.9760, 80.5547, 940.0, 1.0000, 513.0000, 1026.0],+ [346.7947, 262.1440, 86.96, 2.3653, 509.9280, 1570.886],+ [392.1920, 144.2067, 469.42, 255.9760, 411.1292, 774.28],+ ],+ [+ [139.2640, 103.0150, 283.162, 398.3120, 411.5225, 454.185],+ [1.0240, 80.5547, 469.50, 513.0000, 513.0000, 513.0],+ [165.2053, 262.1440, 42.98, 511.6347, 509.9280, 785.443],+ [119.8080, 144.2067, 234.21, 258.0240, 411.1292, 387.14],+ ],+ ],+ device=device,+ dtype=dtype,+ )++ trans_mat = torch.tensor(+ [+ [[-1.0, 0.0, 0.0, 512.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 2.0, 1.0], [0.0, 0.0, 0.0, 1.0]],+ [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]],+ ],+ device=device,+ dtype=dtype,+ )++ boxes = Boxes3D.from_tensor(boxes_xyzxyz)+ 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)++ def test_gradcheck(self, device, dtype):+ # Define boxes in XYZXYZ format for simplicity.+ boxes_xyzxyz = torch.tensor(+ [+ [139.2640, 103.0150, 283.162, 397.3120, 410.5225, 453.185],+ [1.0240, 80.5547, 469.50, 512.0000, 512.0000, 512.0],+ [165.2053, 262.1440, 42.98, 510.6347, 508.9280, 784.443],+ [119.8080, 144.2067, 234.21, 257.0240, 410.1292, 386.14],+ ],+ device=device,+ dtype=dtype,+ )+ boxes = Boxes3D.from_tensor(boxes_xyzxyz)++ trans_mat = torch.tensor(+ [[[-1.0, 0.0, 0.0, 512.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 2.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)++ def _wrapper_transform_boxes(hexahedrons, M):+ boxes = Boxes3D(hexahedrons)+ boxes = boxes.transform_boxes(M)+ return boxes._boxes++ assert gradcheck(_wrapper_transform_boxes, (t_boxes, trans_mat), raise_exception=True)