Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Moving bbox-related functionality to bbox module (#1103)

Daniel Koguciuk456824fec301
diff --git a/docs/source/geometry.bbox.rst b/docs/source/geometry.bbox.rst
new file mode 100644
index 000000000..266c9efbc
--- /dev/null
+++ b/docs/source/geometry.bbox.rst
@@ -0,0 +1,7 @@
+kornia.geometry.homography
+==========================
+
+Module with useful functionalities for 2D and 3D bounding boxes manipulation.
+
+.. automodule:: kornia.geometry.bbox
+ :members:
diff --git a/docs/source/geometry.rst b/docs/source/geometry.rst
index 959a2e76a..7334c35f7 100644
--- a/docs/source/geometry.rst
+++ b/docs/source/geometry.rst
@@ -6,6 +6,7 @@ kornia.geometry
.. toctree::
:maxdepth: 2
+ geometry.bbox
geometry.calibration
geometry.camera
geometry.conversions
diff --git a/docs/source/governance.rst b/docs/source/governance.rst
index 233dceb6c..10da4a47f 100644
--- a/docs/source/governance.rst
+++ b/docs/source/governance.rst
@@ -42,7 +42,7 @@ Module-level maintainers
- Edgar Riba (`edgarriba <https://github.com/edgarriba>`__)
- Dmytro Mishkin (`ducha-aiki <https://github.com/ducha-aiki>`__)
- Daniel Koguciuk (`dkoguciuk <https://github.com/dkoguciuk>`__)
-- Duc Nguyen (`justanhduc <https://github.com/justanhduc>`__)
+- Duc Nguyen (`justanhduc <https://github.com/justanhduc>`__)
**kornia.feature**
~~~~~~~~~~~~~~~~~~
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 0865d1d8c..1ef0942ec 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -7,7 +7,8 @@ import torch.nn as nn
from kornia.augmentation.base import _AugmentationBase, GeometricAugmentationBase2D, IntensityAugmentationBase2D
from kornia.constants import DataKey
-from kornia.geometry import transform_boxes, transform_points
+from kornia.geometry.bbox import transform_bbox
+from kornia.geometry.linalg import transform_points
from .image import ImageSequential, ParamItem
from .patch import PatchSequential
@@ -126,7 +127,7 @@ class AugmentationSequential(ImageSequential):
if isinstance(module, GeometricAugmentationBase2D) and _param is None:
raise ValueError(f"Transformation matrix for {module} has not been computed.")
if isinstance(module, GeometricAugmentationBase2D) and _param is not None:
- input = transform_boxes(module.get_transformation_matrix(input, _param), input, mode)
+ input = transform_bbox(module.get_transformation_matrix(input, _param), input, mode)
else:
pass # No need to update anything
return input
@@ -200,7 +201,7 @@ class AugmentationSequential(ImageSequential):
) -> torch.Tensor:
if isinstance(module, GeometricAugmentationBase2D):
transform = module.compute_inverse_transformation(module.get_transformation_matrix(input, param))
- input = transform_boxes(torch.as_tensor(transform, device=input.device, dtype=input.dtype), input, mode)
+ input = transform_bbox(torch.as_tensor(transform, device=input.device, dtype=input.dtype), input, mode)
return input
def inverse_keypoints(
diff --git a/kornia/augmentation/mix_augmentation.py b/kornia/augmentation/mix_augmentation.py
index 7227867d2..aed741467 100644
--- a/kornia/augmentation/mix_augmentation.py
+++ b/kornia/augmentation/mix_augmentation.py
@@ -2,7 +2,7 @@ from typing import cast, Dict, Optional, Tuple, Union
import torch
-from kornia.geometry import bbox_to_mask, infer_box_shape
+from kornia.geometry.bbox import bbox_to_mask, infer_bbox_shape
from . import random_generator as rg
from .base import MixAugmentationBase
@@ -269,7 +269,7 @@ class RandomCutMix(MixAugmentationBase):
for pair, crop in zip(params['mix_pairs'], params['crop_src']):
input_permute = input.index_select(dim=0, index=pair.to(input.device))
labels_permute = label.index_select(dim=0, index=pair.to(label.device))
- w, h = infer_box_shape(crop)
+ w, h = infer_bbox_shape(crop)
lam = w.to(input.dtype) * h.to(input.dtype) / (width * height) # width_beta * height_beta
# compute mask to match input shape
mask = bbox_to_mask(crop, width, height).bool().unsqueeze(dim=1).repeat(1, input.size(1), 1, 1)
diff --git a/kornia/augmentation/random_generator/random_generator.py b/kornia/augmentation/random_generator/random_generator.py
index 40c9d62f5..c4930450d 100644
--- a/kornia/augmentation/random_generator/random_generator.py
+++ b/kornia/augmentation/random_generator/random_generator.py
@@ -3,7 +3,7 @@ from typing import cast, Dict, Optional, Tuple, Union
import torch
from torch.distributions import Bernoulli
-from kornia.geometry import bbox_generator
+from kornia.geometry.bbox import bbox_generator
from kornia.utils import _extract_device_dtype
from ..utils import _adapted_beta, _adapted_sampling, _adapted_uniform, _common_param_check, _joint_range_check
diff --git a/kornia/augmentation/random_generator/random_generator3d.py b/kornia/augmentation/random_generator/random_generator3d.py
index 37398e1b5..2bb0eef4a 100644
--- a/kornia/augmentation/random_generator/random_generator3d.py
+++ b/kornia/augmentation/random_generator/random_generator3d.py
@@ -2,7 +2,7 @@ from typing import Dict, Optional, Tuple, Union
import torch
-from kornia.geometry import bbox_generator3d
+from kornia.geometry.bbox import bbox_generator3d
from kornia.utils import _extract_device_dtype
from ..utils import _adapted_uniform, _joint_range_check
diff --git a/kornia/geometry/__init__.py b/kornia/geometry/__init__.py
index 711c338bc..03d1eb528 100644
--- a/kornia/geometry/__init__.py
+++ b/kornia/geometry/__init__.py
@@ -1,3 +1,4 @@
+from kornia.geometry.bbox import *
from kornia.geometry.calibration import *
from kornia.geometry.camera import *
from kornia.geometry.conversions import *
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
new file mode 100644
index 000000000..5266db9b5
--- /dev/null
+++ b/kornia/geometry/bbox.py
@@ -0,0 +1,482 @@
+from typing import Tuple
+
+import torch
+
+import kornia
+
+
+def validate_bbox(boxes: torch.Tensor) -> bool:
+ """Validate if a 2D bounding box usable or not. This function checks if the boxes are rectangular or not.
+
+ Args:
+ boxes (torch.Tensor): a tensor containing the coordinates of the
+ bounding boxes to be extracted. The tensor must have the shape
+ of Bx4x2, where each box is defined in the following (clockwise)
+ order: top-left, top-right, bottom-right, bottom-left. The
+ coordinates must be in the x, y order.
+ """
+ assert len(boxes.shape) == 3 and boxes.shape[1:] == torch.Size(
+ [4, 2]
+ ), f"Box shape must be (B, 4, 2). Got {boxes.shape}."
+
+ if not torch.allclose((boxes[:, 1, 0] - boxes[:, 0, 0] + 1), (boxes[:, 2, 0] - boxes[:, 3, 0] + 1)):
+ raise ValueError(
+ "Boxes must have be rectangular, while get widths %s and %s"
+ % (str(boxes[:, 1, 0] - boxes[:, 0, 0] + 1), str(boxes[:, 2, 0] - boxes[:, 3, 0] + 1))
+ )
+
+ if not torch.allclose((boxes[:, 2, 1] - boxes[:, 0, 1] + 1), (boxes[:, 3, 1] - boxes[:, 1, 1] + 1)):
+ raise ValueError(
+ "Boxes must have be rectangular, while get heights %s and %s"
+ % (str(boxes[:, 2, 1] - boxes[:, 0, 1] + 1), str(boxes[:, 3, 1] - boxes[:, 1, 1] + 1))
+ )
+
+ return True
+
+
+def validate_bbox3d(boxes: torch.Tensor) -> bool:
+ """Validate if a 3D bounding box usable or not. This function checks if the boxes are cube or not.
+
+ Args:
+ boxes (torch.Tensor): a tensor containing the coordinates of the bounding boxes to be extracted.
+ The tensor must have the shape of Bx8x3, where each box is defined 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. The coordinates must be in the x, y, z order.
+ """
+ assert len(boxes.shape) == 3 and boxes.shape[1:] == torch.Size(
+ [8, 3]
+ ), f"Box shape must be (B, 8, 3). Got {boxes.shape}."
+
+ left = torch.index_select(boxes, 1, torch.tensor([1, 2, 5, 6], device=boxes.device, dtype=torch.long))[:, :, 0]
+ right = torch.index_select(boxes, 1, torch.tensor([0, 3, 4, 7], device=boxes.device, dtype=torch.long))[:, :, 0]
+ widths = left - right + 1
+ assert torch.allclose(
+ widths.permute(1, 0), widths[:, 0]
+ ), f"Boxes must have be cube, while get different widths {widths}."
+
+ bot = torch.index_select(boxes, 1, torch.tensor([2, 3, 6, 7], device=boxes.device, dtype=torch.long))[:, :, 1]
+ upper = torch.index_select(boxes, 1, torch.tensor([0, 1, 4, 5], device=boxes.device, dtype=torch.long))[:, :, 1]
+ heights = bot - upper + 1
+ assert torch.allclose(
+ heights.permute(1, 0), heights[:, 0]
+ ), f"Boxes must have be cube, while get different heights {heights}."
+
+ depths = boxes[:, 4:, 2] - boxes[:, :4, 2] + 1
+ assert torch.allclose(
+ depths.permute(1, 0), depths[:, 0]
+ ), f"Boxes must have be cube, while get different depths {depths}."
+
+ return True
+
+
+def infer_bbox_shape(boxes: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ r"""Auto-infer the output sizes for the given 2D bounding boxes.
+
+ Args:
+ boxes (torch.Tensor): a tensor containing the coordinates of the
+ bounding boxes to be extracted. The tensor must have the shape
+ of Bx4x2, where each box is defined in the following (clockwise)
+ order: top-left, top-right, bottom-right, bottom-left. The
+ coordinates must be in the x, y order.
+
+ Returns:
+ Tuple[torch.Tensor, torch.Tensor]:
+ - Bounding box heights, shape of :math:`(B,)`.
+ - Boundingbox widths, shape of :math:`(B,)`.
+
+ Example:
+ >>> boxes = torch.tensor([[
+ ... [1., 1.],
+ ... [2., 1.],
+ ... [2., 2.],
+ ... [1., 2.],
+ ... ], [
+ ... [1., 1.],
+ ... [3., 1.],
+ ... [3., 2.],
+ ... [1., 2.],
+ ... ]]) # 2x4x2
+ >>> infer_bbox_shape(boxes)
+ (tensor([2., 2.]), tensor([2., 3.]))
+ """
+ validate_bbox(boxes)
+ width: torch.Tensor = boxes[:, 1, 0] - boxes[:, 0, 0] + 1
+ height: torch.Tensor = boxes[:, 2, 1] - boxes[:, 0, 1] + 1
+ return height, width
+
+
+def infer_bbox_shape3d(boxes: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ r"""Auto-infer the output sizes for the given 3D bounding boxes.
+
+ Args:
+ boxes (torch.Tensor): a tensor containing the coordinates of the bounding boxes to be extracted.
+ The tensor must have the shape of Bx8x3, where each box is defined 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. The coordinates must be in the x, y, z order.
+
+ Returns:
+ Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ - Bounding box depths, shape of :math:`(B,)`.
+ - Bounding box heights, shape of :math:`(B,)`.
+ - Bounding box widths, shape of :math:`(B,)`.
+
+ Example:
+ >>> boxes = 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]],
+ ... [[ 3, 4, 5],
+ ... [43, 4, 5],
+ ... [43, 54, 5],
+ ... [ 3, 54, 5],
+ ... [ 3, 4, 65],
+ ... [43, 4, 65],
+ ... [43, 54, 65],
+ ... [ 3, 54, 65]]]) # 2x8x3
+ >>> infer_bbox_shape3d(boxes)
+ (tensor([31, 61]), tensor([21, 51]), tensor([11, 41]))
+ """
+ validate_bbox3d(boxes)
+
+ left = torch.index_select(boxes, 1, torch.tensor([1, 2, 5, 6], device=boxes.device, dtype=torch.long))[:, :, 0]
+ right = torch.index_select(boxes, 1, torch.tensor([0, 3, 4, 7], device=boxes.device, dtype=torch.long))[:, :, 0]
+ widths = (left - right + 1)[:, 0]
+
+ bot = torch.index_select(boxes, 1, torch.tensor([2, 3, 6, 7], device=boxes.device, dtype=torch.long))[:, :, 1]
+ upper = torch.index_select(boxes, 1, torch.tensor([0, 1, 4, 5], device=boxes.device, dtype=torch.long))[:, :, 1]
+ heights = (bot - upper + 1)[:, 0]
+
+ depths = (boxes[:, 4:, 2] - boxes[:, :4, 2] + 1)[:, 0]
+ return depths, heights, widths
+
+
+def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
+ """Convert 2D bounding boxes to masks. Covered area is 1. and the remaining is 0.
+
+ Args:
+ boxes (torch.Tensor): a tensor containing the coordinates of the bounding boxes to be extracted.
+ The tensor must have the shape of Bx4x2, where each box is defined in the following (clockwise)
+ order: top-left, top-right, bottom-right and bottom-left. The coordinates must be in the x, y order.
+ width (int): width of the masked image.
+ height (int): height of the masked image.
+
+ Returns:
+ torch.Tensor: the output mask tensor.
+
+ Note:
+ It is currently non-differentiable.
+
+ Examples:
+ >>> boxes = torch.tensor([[
+ ... [1., 1.],
+ ... [3., 1.],
+ ... [3., 2.],
+ ... [1., 2.],
+ ... ]]) # 1x4x2
+ >>> bbox_to_mask(boxes, 5, 5)
+ 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.]]])
+ """
+ validate_bbox(boxes)
+ # zero padding the surroudings
+ mask = torch.zeros((len(boxes), height + 2, width + 2))
+ # push all points one pixel off
+ # in order to zero-out the fully filled rows or columns
+ boxes += 1
+
+ mask_out = []
+ # TODO: Looking for a vectorized way
+ for m, box in zip(mask, boxes):
+ m = m.index_fill(1, torch.arange(box[0, 0].item(), box[1, 0].item() + 1, dtype=torch.long), torch.tensor(1))
+ m = m.index_fill(0, torch.arange(box[1, 1].item(), box[2, 1].item() + 1, dtype=torch.long), torch.tensor(1))
+ m = m.unsqueeze(dim=0)
+ m_out = (m == 1).all(dim=1) * (m == 1).all(dim=2).T
+ m_out = m_out[1:-1, 1:-1]
+ mask_out.append(m_out)
+
+ return torch.stack(mask_out, dim=0).float()
+
+
+def bbox_to_mask3d(boxes: torch.Tensor, size: Tuple[int, int, int]) -> torch.Tensor:
+ """Convert 3D bounding boxes to masks. Covered area is 1. and the remaining is 0.
+
+ Args:
+ boxes (torch.Tensor): a tensor containing the coordinates of the bounding boxes to be extracted.
+ The tensor must have the shape of Bx8x3, where each box is defined 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. The coordinates must be in the x, y, z order.
+ size (Tuple[int, int, int]): depth, height and width of the masked image.
+
+ Returns:
+ torch.Tensor: the output mask tensor.
+
+ Examples:
+ >>> boxes = torch.tensor([[
+ ... [1., 1., 1.],
+ ... [2., 1., 1.],
+ ... [2., 2., 1.],
+ ... [1., 2., 1.],
+ ... [1., 1., 2.],
+ ... [2., 1., 2.],
+ ... [2., 2., 2.],
+ ... [1., 2., 2.],
+ ... ]]) # 1x8x3
+ >>> bbox_to_mask3d(boxes, (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., 0., 0.],
+ [0., 1., 1., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.]],
+ <BLANKLINE>
+ [[0., 0., 0., 0., 0.],
+ [0., 1., 1., 0., 0.],
+ [0., 1., 1., 0., 0.],
+ [0., 0., 0., 0., 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.]]]]])
+ """
+ validate_bbox3d(boxes)
+ mask = torch.zeros((len(boxes), *size))
+
+ mask_out = []
+ # TODO: Looking for a vectorized way
+ for m, box in zip(mask, boxes):
+ m = m.index_fill(
+ 0,
+ torch.arange(box[0, 2].item(), box[4, 2].item() + 1, device=box.device, dtype=torch.long),
+ torch.tensor(1, device=box.device, dtype=box.dtype),
+ )
+ m = m.index_fill(
+ 1,
+ torch.arange(box[1, 1].item(), box[2, 1].item() + 1, device=box.device, dtype=torch.long),
+ torch.tensor(1, device=box.device, dtype=box.dtype),
+ )
+ m = m.index_fill(
+ 2,
+ torch.arange(box[0, 0].item(), box[1, 0].item() + 1, device=box.device, dtype=torch.long),
+ torch.tensor(1, device=box.device, dtype=box.dtype),
+ )
+ m = m.unsqueeze(dim=0)
+ m_out = torch.ones_like(m)
+ m_out = m_out * (m == 1).all(dim=2, keepdim=True).all(dim=1, keepdim=True)
+ m_out = m_out * (m == 1).all(dim=3, keepdim=True).all(dim=1, keepdim=True)
+ m_out = m_out * (m == 1).all(dim=2, keepdim=True).all(dim=3, keepdim=True)
+ mask_out.append(m_out)
+
+ return torch.stack(mask_out, dim=0).float()
+
+
+def bbox_generator(
+ x_start: torch.Tensor, y_start: torch.Tensor, width: torch.Tensor, height: torch.Tensor
+) -> torch.Tensor:
+ """Generate 2D bounding boxes according to the provided start coords, width and height.
+
+ Args:
+ x_start (torch.Tensor): a tensor containing the x coordinates of the bounding boxes to be extracted.
+ Shape must be a scalar tensor or :math:`(B,)`.
+ y_start (torch.Tensor): a tensor containing the y coordinates of the bounding boxes to be extracted.
+ Shape must be a scalar tensor or :math:`(B,)`.
+ width (torch.Tensor): widths of the masked image.
+ Shape must be a scalar tensor or :math:`(B,)`.
+ height (torch.Tensor): heights of the masked image.
+ Shape must be a scalar tensor or :math:`(B,)`.
+
+ Returns:
+ torch.Tensor: the bounding box tensor.
+
+ Examples:
+ >>> x_start = torch.tensor([0, 1])
+ >>> y_start = torch.tensor([1, 0])
+ >>> width = torch.tensor([5, 3])
+ >>> height = torch.tensor([7, 4])
+ >>> bbox_generator(x_start, y_start, width, height)
+ tensor([[[0, 1],
+ [4, 1],
+ [4, 7],
+ [0, 7]],
+ <BLANKLINE>
+ [[1, 0],
+ [3, 0],
+ [3, 3],
+ [1, 3]]])
+ """
+ assert x_start.shape == y_start.shape and x_start.dim() in [
+ 0,
+ 1,
+ ], f"`x_start` and `y_start` must be a scalar or (B,). Got {x_start}, {y_start}."
+ assert width.shape == height.shape and width.dim() in [
+ 0,
+ 1,
+ ], f"`width` and `height` must be a scalar or (B,). Got {width}, {height}."
+ assert x_start.dtype == y_start.dtype == width.dtype == height.dtype, (
+ "All tensors must be in the same dtype. Got "
+ f"`x_start`({x_start.dtype}), `y_start`({x_start.dtype}), `width`({width.dtype}), `height`({height.dtype})."
+ )
+ assert x_start.device == y_start.device == width.device == height.device, (
+ "All tensors must be in the same device. Got "
+ f"`x_start`({x_start.device}), `y_start`({x_start.device}), `width`({width.device}), `height`({height.device})."
+ )
+
+ bbox = torch.tensor([[[0, 0], [0, 0], [0, 0], [0, 0]]], device=x_start.device, dtype=x_start.dtype).repeat(
+ 1 if x_start.dim() == 0 else len(x_start), 1, 1
+ )
+
+ bbox[:, :, 0] += x_start.view(-1, 1)
+ bbox[:, :, 1] += y_start.view(-1, 1)
+ bbox[:, 1, 0] += width - 1
+ bbox[:, 2, 0] += width - 1
+ bbox[:, 2, 1] += height - 1
+ bbox[:, 3, 1] += height - 1
+
+ return bbox
+
+
+def bbox_generator3d(
+ x_start: torch.Tensor,
+ y_start: torch.Tensor,
+ z_start: torch.Tensor,
+ width: torch.Tensor,
+ height: torch.Tensor,
+ depth: torch.Tensor,
+) -> torch.Tensor:
+ """Generate 3D bounding boxes according to the provided start coords, width, height and depth.
+
+ Args:
+ x_start (torch.Tensor): a tensor containing the x coordinates of the bounding boxes to be extracted.
+ Shape must be a scalar tensor or :math:`(B,)`.
+ y_start (torch.Tensor): a tensor containing the y coordinates of the bounding boxes to be extracted.
+ Shape must be a scalar tensor or :math:`(B,)`.
+ z_start (torch.Tensor): a tensor containing the z coordinates of the bounding boxes to be extracted.
+ Shape must be a scalar tensor or :math:`(B,)`.
+ width (torch.Tensor): widths of the masked image.
+ Shape must be a scalar tensor or :math:`(B,)`.
+ height (torch.Tensor): heights of the masked image.
+ Shape must be a scalar tensor or :math:`(B,)`.
+ depth (torch.Tensor): depths of the masked image.
+ Shape must be a scalar tensor or :math:`(B,)`.
+
+ Returns:
+ torch.Tensor: the 3d bounding box tensor :math:`(B, 8, 3)`.
+
+ Examples:
+ >>> x_start = torch.tensor([0, 3])
+ >>> y_start = torch.tensor([1, 4])
+ >>> z_start = torch.tensor([2, 5])
+ >>> width = torch.tensor([10, 40])
+ >>> height = torch.tensor([20, 50])
+ >>> depth = torch.tensor([30, 60])
+ >>> bbox_generator3d(x_start, y_start, z_start, width, height, depth)
+ 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]],
+ <BLANKLINE>
+ [[ 3, 4, 5],
+ [43, 4, 5],
+ [43, 54, 5],
+ [ 3, 54, 5],
+ [ 3, 4, 65],
+ [43, 4, 65],
+ [43, 54, 65],
+ [ 3, 54, 65]]])
+ """
+ assert x_start.shape == y_start.shape == z_start.shape and x_start.dim() in [
+ 0,
+ 1,
+ ], f"`x_start`, `y_start` and `z_start` must be a scalar or (B,). Got {x_start}, {y_start}, {z_start}."
+ assert width.shape == height.shape == depth.shape and width.dim() in [
+ 0,
+ 1,
+ ], f"`width`, `height` and `depth` must be a scalar or (B,). Got {width}, {height}, {depth}."
+ assert x_start.dtype == y_start.dtype == z_start.dtype == width.dtype == height.dtype == depth.dtype, (
+ "All tensors must be in the same dtype. "
+ f"Got `x_start`({x_start.dtype}), `y_start`({x_start.dtype}), `z_start`({x_start.dtype}), "
+ f"`width`({width.dtype}), `height`({height.dtype}) and `depth`({depth.dtype})."
+ )
+ assert x_start.device == y_start.device == z_start.device == width.device == height.device == depth.device, (
+ "All tensors must be in the same device. "
+ f"Got `x_start`({x_start.device}), `y_start`({x_start.device}), `z_start`({x_start.device}), "
+ f"`width`({width.device}), `height`({height.device}) and `depth`({depth.device})."
+ )
+
+ # front
+ bbox = torch.tensor(
+ [[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]], device=x_start.device, dtype=x_start.dtype
+ ).repeat(len(x_start), 1, 1)
+
+ bbox[:, :, 0] += x_start.view(-1, 1)
+ bbox[:, :, 1] += y_start.view(-1, 1)
+ bbox[:, :, 2] += z_start.view(-1, 1)
+ bbox[:, 1, 0] += width
+ bbox[:, 2, 0] += width
+ bbox[:, 2, 1] += height
+ bbox[:, 3, 1] += height
+
+ # back
+ bbox_back = bbox.clone()
+ bbox_back[:, :, -1] += depth.unsqueeze(dim=1).repeat(1, 4)
+ bbox = torch.cat([bbox, bbox_back], dim=1)
+
+ return bbox
+
+
+def transform_bbox(trans_mat: torch.Tensor, boxes: torch.Tensor, mode: str = "xyxy") -> 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)
+
+ Args:
+ trans_mat (torch.Tensor): The transformation matrix to be applied
+ boxes (torch.Tensor): The boxes to be transformed
+ mode (str): 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).
+ Default: 'xyxy'
+ Returns:
+ torch.Tensor: The set of transformed points in the specified mode
+
+
+ """
+ if not isinstance(mode, str):
+ raise TypeError(f"Mode must be a string. Got {type(mode)}")
+
+ if mode not in ("xyxy", "xywh"):
+ raise ValueError(f"Mode must be one of 'xyxy', 'xywh'. Got {mode}")
+
+ # convert boxes to format xyxy
+ if mode == "xywh":
+ boxes[..., -2] = boxes[..., 0] + boxes[..., -2] # x + w
+ boxes[..., -1] = boxes[..., 1] + boxes[..., -1] # y + h
+
+ transformed_boxes: torch.Tensor = kornia.transform_points(trans_mat, boxes.view(boxes.shape[0], -1, 2))
+ transformed_boxes = transformed_boxes.view_as(boxes)
+
+ if mode == 'xywh':
+ transformed_boxes[..., 2] = transformed_boxes[..., 2] - transformed_boxes[..., 0]
+ transformed_boxes[..., 3] = transformed_boxes[..., 3] - transformed_boxes[..., 1]
+
+ return transformed_boxes
diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.py
index 18262d91c..cac02781a 100644
--- a/kornia/geometry/linalg.py
+++ b/kornia/geometry/linalg.py
@@ -1,6 +1,9 @@
+import warnings
+
import torch
import kornia
+from kornia.geometry.bbox import transform_bbox as _transform_bbox
from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
from kornia.testing import check_is_tensor
@@ -222,26 +225,13 @@ def transform_boxes(trans_mat: torch.Tensor, boxes: torch.Tensor, mode: str = "x
"""
-
- if not isinstance(mode, str):
- raise TypeError(f"Mode must be a string. Got {type(mode)}")
-
- if mode not in ("xyxy", "xywh"):
- raise ValueError(f"Mode must be one of 'xyxy', 'xywh'. Got {mode}")
-
- # convert boxes to format xyxy
- if mode == "xywh":
- boxes[..., -2] = boxes[..., 0] + boxes[..., -2] # x + w
- boxes[..., -1] = boxes[..., 1] + boxes[..., -1] # y + h
-
- transformed_boxes: torch.Tensor = kornia.transform_points(trans_mat, boxes.view(boxes.shape[0], -1, 2))
- transformed_boxes = transformed_boxes.view_as(boxes)
-
- if mode == 'xywh':
- transformed_boxes[..., 2] = transformed_boxes[..., 2] - transformed_boxes[..., 0]
- transformed_boxes[..., 3] = transformed_boxes[..., 3] - transformed_boxes[..., 1]
-
- return transformed_boxes
+ warnings.warn(
+ "`kornia.geometry.linalg.transform_boxes` is deprecated and will be removed > 0.6.0. "
+ "Please use `kornia.geometry.bbox.transform_bbox instead.`",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return _transform_bbox(trans_mat, boxes, mode)
def perspective_transform_lafs(trans_01: torch.Tensor, lafs_1: torch.Tensor) -> torch.Tensor:
diff --git a/kornia/geometry/transform/crop/crop2d.py b/kornia/geometry/transform/crop/crop2d.py
index bc5927c35..cdc8dd709 100644
--- a/kornia/geometry/transform/crop/crop2d.py
+++ b/kornia/geometry/transform/crop/crop2d.py
@@ -1,7 +1,12 @@
+import warnings
from typing import Optional, Tuple
import torch
+from kornia.geometry.bbox import bbox_generator as _bbox_generator
+from kornia.geometry.bbox import bbox_to_mask as _bbox_to_mask
+from kornia.geometry.bbox import infer_bbox_shape as _infer_bbox_shape
+from kornia.geometry.bbox import validate_bbox as _validate_bbox
from kornia.geometry.transform.imgwarp import get_perspective_transform, warp_affine
__all__ = [
@@ -9,9 +14,9 @@ __all__ = [
"crop_by_boxes",
"crop_by_transform_mat",
"center_crop",
- "bbox_to_mask",
- "infer_box_shape",
"validate_bboxes",
+ "infer_box_shape",
+ "bbox_to_mask",
"bbox_generator",
]
@@ -216,8 +221,8 @@ def crop_by_boxes(
RuntimeError: solve_cpu: For batch 0: U(2,2) is zero, singular U.
"""
# TODO: improve this since might slow down the function
- validate_bboxes(src_box)
- validate_bboxes(dst_box)
+ _validate_bbox(src_box)
+ _validate_bbox(dst_box)
assert len(tensor.shape) == 4, f"Only tensor with shape (B, C, H, W) supported. Got {tensor.shape}."
@@ -225,7 +230,7 @@ def crop_by_boxes(
# Note: Tensor.dtype must be float. "solve_cpu" not implemented for 'Long'
dst_trans_src: torch.Tensor = get_perspective_transform(src_box.to(tensor), dst_box.to(tensor))
- bbox: Tuple[torch.Tensor, torch.Tensor] = infer_box_shape(dst_box)
+ bbox: Tuple[torch.Tensor, torch.Tensor] = _infer_bbox_shape(dst_box)
assert (bbox[0] == bbox[0][0]).all() and (bbox[1] == bbox[1][0]).all(), (
f"Cropping height, width and depth must be exact same in a batch. " f"Got height {bbox[0]} and width {bbox[1]}."
)
@@ -271,6 +276,27 @@ def crop_by_transform_mat(
return patches
+def validate_bboxes(boxes: torch.Tensor) -> bool:
+ """Validate if a 2D bounding box usable or not.
+ This function checks if the boxes are rectangular or not.
+ Args:
+ boxes (torch.Tensor): a tensor containing the coordinates of the
+ bounding boxes to be extracted. The tensor must have the shape
+ of Bx4x2, where each box is defined in the following (clockwise)
+ order: top-left, top-right, bottom-right, bottom-left. The
+ coordinates must be in the x, y order.
+
+ """
+ warnings.warn(
+ "`kornia.geometry.transforms.crop.crop2d.validate_bboxes` is deprecated and will be removed > 0.6.0. "
+ "Please use `kornia.geometry.bbox.validate_bbox instead.`",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return _validate_bbox(boxes)
+
+
def infer_box_shape(boxes: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Auto-infer the output sizes for the given 2D bounding boxes.
@@ -301,38 +327,13 @@ def infer_box_shape(boxes: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
>>> infer_box_shape(boxes)
(tensor([2., 2.]), tensor([2., 3.]))
"""
- validate_bboxes(boxes)
- width: torch.Tensor = boxes[:, 1, 0] - boxes[:, 0, 0] + 1
- height: torch.Tensor = boxes[:, 2, 1] - boxes[:, 0, 1] + 1
- return (height, width)
-
-
-def validate_bboxes(boxes: torch.Tensor) -> bool:
- """Validate if a 2D bounding box usable or not.
-
- This function checks if the boxes are rectangular or not.
-
- Args:
- boxes (torch.Tensor): a tensor containing the coordinates of the
- bounding boxes to be extracted. The tensor must have the shape
- of Bx4x2, where each box is defined in the following (clockwise)
- order: top-left, top-right, bottom-right, bottom-left. The
- coordinates must be in the x, y order.
- """
- if not torch.allclose((boxes[:, 1, 0] - boxes[:, 0, 0] + 1), (boxes[:, 2, 0] - boxes[:, 3, 0] + 1)):
- raise ValueError(
- "Boxes must have be rectangular, while get widths %s and %s"
- % (str(boxes[:, 1, 0] - boxes[:, 0, 0] + 1), str(boxes[:, 2, 0] - boxes[:, 3, 0] + 1))
- )
-
- if not torch.allclose((boxes[:, 2, 1] - boxes[:, 0, 1] + 1), (boxes[:, 3, 1] - boxes[:, 1, 1] + 1)):
- raise ValueError(
- "Boxes must have be rectangular, while get heights %s and %s"
- % (str(boxes[:, 2, 1] - boxes[:, 0, 1] + 1), str(boxes[:, 3, 1] - boxes[:, 1, 1] + 1))
- )
-
- return True
+ warnings.warn(
+ "`kornia.geometry.transforms.crop.crop2d.infer_box_shape` is deprecated and will be removed > 0.6.0. "
+ "Please use `kornia.geometry.bbox.infer_bbox_shape instead.`",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return _infer_bbox_shape(boxes)
def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
@@ -365,24 +366,13 @@ def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]]])
"""
- validate_bboxes(boxes)
- # zero padding the surroudings
- mask = torch.zeros((len(boxes), height + 2, width + 2))
- # push all points one pixel off
- # in order to zero-out the fully filled rows or columns
- boxes += 1
-
- mask_out = []
- # TODO: Looking for a vectorized way
- for m, box in zip(mask, boxes):
- m = m.index_fill(1, torch.arange(box[0, 0].item(), box[1, 0].item() + 1, dtype=torch.long), torch.tensor(1))
- m = m.index_fill(0, torch.arange(box[1, 1].item(), box[2, 1].item() + 1, dtype=torch.long), torch.tensor(1))
- m = m.unsqueeze(dim=0)
- m_out = (m == 1).all(dim=1) * (m == 1).all(dim=2).T
- m_out = m_out[1:-1, 1:-1]
- mask_out.append(m_out)
-
- return torch.stack(mask_out, dim=0).float()
+ warnings.warn(
+ "`kornia.geometry.transforms.crop.crop2d.bbox_to_mask` is deprecated and will be removed > 0.6.0. "
+ "Please use `kornia.geometry.bbox.bbox_to_mask instead.`",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return _bbox_to_mask(boxes, width, height)
def bbox_generator(
@@ -419,32 +409,10 @@ def bbox_generator(
[3, 3],
[1, 3]]])
"""
- assert x_start.shape == y_start.shape and x_start.dim() in [
- 0,
- 1,
- ], f"`x_start` and `y_start` must be a scalar or (B,). Got {x_start}, {y_start}."
- assert width.shape == height.shape and width.dim() in [
- 0,
- 1,
- ], f"`width` and `height` must be a scalar or (B,). Got {width}, {height}."
- assert x_start.dtype == y_start.dtype == width.dtype == height.dtype, (
- "All tensors must be in the same dtype. Got "
- f"`x_start`({x_start.dtype}), `y_start`({x_start.dtype}), `width`({width.dtype}), `height`({height.dtype})."
+ warnings.warn(
+ "`kornia.geometry.transforms.crop.crop2d.bbox_generator` is deprecated and will be removed > 0.6.0. "
+ "Please use `kornia.geometry.bbox.bbox_generator instead.`",
+ DeprecationWarning,
+ stacklevel=2,
)
- assert x_start.device == y_start.device == width.device == height.device, (
- "All tensors must be in the same device. Got "
- f"`x_start`({x_start.device}), `y_start`({x_start.device}), `width`({width.device}), `height`({height.device})."
- )
-
- bbox = torch.tensor([[[0, 0], [0, 0], [0, 0], [0, 0]]], device=x_start.device, dtype=x_start.dtype).repeat(
- 1 if x_start.dim() == 0 else len(x_start), 1, 1
- )
-
- bbox[:, :, 0] += x_start.view(-1, 1)
- bbox[:, :, 1] += y_start.view(-1, 1)
- bbox[:, 1, 0] += width - 1
- bbox[:, 2, 0] += width - 1
- bbox[:, 2, 1] += height - 1
- bbox[:, 3, 1] += height - 1
-
- return bbox
+ return _bbox_generator(x_start, y_start, width, height)
diff --git a/kornia/geometry/transform/crop/crop3d.py b/kornia/geometry/transform/crop/crop3d.py
index 0a6b38477..1e860f79a 100644
--- a/kornia/geometry/transform/crop/crop3d.py
+++ b/kornia/geometry/transform/crop/crop3d.py
@@ -1,7 +1,12 @@
+import warnings
from typing import Optional, Tuple
import torch
+from kornia.geometry.bbox import bbox_generator3d as _bbox_generator3d
+from kornia.geometry.bbox import bbox_to_mask3d as _bbox_to_mask3d
+from kornia.geometry.bbox import infer_bbox_shape3d as _infer_bbox_shape3d
+from kornia.geometry.bbox import validate_bbox3d as _validate_bbox3d
from kornia.geometry.transform.projwarp import get_perspective_transform3d, warp_affine3d
__all__ = [
@@ -9,9 +14,9 @@ __all__ = [
"crop_by_boxes3d",
"crop_by_transform_mat3d",
"center_crop3d",
- "bbox_to_mask3d",
- "infer_box_shape3d",
"validate_bboxes3d",
+ "infer_box_shape3d",
+ "bbox_to_mask3d",
"bbox_generator3d",
]
@@ -304,8 +309,8 @@ def crop_by_boxes3d(
[45., 46., 47.]]]]])
"""
- validate_bboxes3d(src_box)
- validate_bboxes3d(dst_box)
+ _validate_bbox3d(src_box)
+ _validate_bbox3d(dst_box)
assert len(tensor.shape) == 5, f"Only tensor with shape (B, C, D, H, W) supported. Got {tensor.shape}."
@@ -315,7 +320,7 @@ def crop_by_boxes3d(
# simulate broadcasting
dst_trans_src = dst_trans_src.expand(tensor.shape[0], -1, -1).type_as(tensor)
- bbox = infer_box_shape3d(dst_box)
+ bbox = _infer_bbox_shape3d(dst_box)
assert (bbox[0] == bbox[0][0]).all() and (bbox[1] == bbox[1][0]).all() and (bbox[2] == bbox[2][0]).all(), (
"Cropping height, width and depth must be exact same in a batch."
f"Got height {bbox[0]}, width {bbox[1]} and depth {bbox[2]}."
@@ -365,6 +370,25 @@ def crop_by_transform_mat3d(
return patches
+def validate_bboxes3d(boxes: torch.Tensor) -> bool:
+ """Validate if a 3D bounding box usable or not.
+ This function checks if the boxes are cube or not.
+ Args:
+ boxes (torch.Tensor): a tensor containing the coordinates of the bounding boxes to be extracted.
+ The tensor must have the shape of Bx8x3, where each box is defined 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. The coordinates must be in the x, y, z order.
+ """
+ warnings.warn(
+ "`kornia.geometry.transforms.crop.crop3d.validate_bboxes3d` is deprecated and will be removed > 0.6.0. "
+ "Please use `kornia.geometry.bbox.validate_bbox3d instead.`",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return _validate_bbox3d(boxes)
+
+
def infer_box_shape3d(boxes: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
r"""Auto-infer the output sizes for the given 3D bounding boxes.
@@ -400,53 +424,13 @@ def infer_box_shape3d(boxes: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor,
>>> infer_box_shape3d(boxes)
(tensor([31, 61]), tensor([21, 51]), tensor([11, 41]))
"""
- validate_bboxes3d(boxes)
-
- left = torch.index_select(boxes, 1, torch.tensor([1, 2, 5, 6], device=boxes.device, dtype=torch.long))[:, :, 0]
- right = torch.index_select(boxes, 1, torch.tensor([0, 3, 4, 7], device=boxes.device, dtype=torch.long))[:, :, 0]
- widths = (left - right + 1)[:, 0]
-
- bot = torch.index_select(boxes, 1, torch.tensor([2, 3, 6, 7], device=boxes.device, dtype=torch.long))[:, :, 1]
- upper = torch.index_select(boxes, 1, torch.tensor([0, 1, 4, 5], device=boxes.device, dtype=torch.long))[:, :, 1]
- heights = (bot - upper + 1)[:, 0]
-
- depths = (boxes[:, 4:, 2] - boxes[:, :4, 2] + 1)[:, 0]
- return (depths, heights, widths)
-
-
-def validate_bboxes3d(boxes: torch.Tensor) -> None:
- """Validate if a 3D bounding box usable or not.
-
- This function checks if the boxes are cube or not.
-
- Args:
- boxes (torch.Tensor): a tensor containing the coordinates of the bounding boxes to be extracted.
- The tensor must have the shape of Bx8x3, where each box is defined 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. The coordinates must be in the x, y, z order.
- """
- assert len(boxes.shape) == 3 and boxes.shape[1:] == torch.Size(
- [8, 3]
- ), f"Box shape must be (B, 8, 3). Got {boxes.shape}."
-
- left = torch.index_select(boxes, 1, torch.tensor([1, 2, 5, 6], device=boxes.device, dtype=torch.long))[:, :, 0]
- right = torch.index_select(boxes, 1, torch.tensor([0, 3, 4, 7], device=boxes.device, dtype=torch.long))[:, :, 0]
- widths = left - right + 1
- assert torch.allclose(
- widths.permute(1, 0), widths[:, 0]
- ), f"Boxes must have be cube, while get different widths {widths}."
-
- bot = torch.index_select(boxes, 1, torch.tensor([2, 3, 6, 7], device=boxes.device, dtype=torch.long))[:, :, 1]
- upper = torch.index_select(boxes, 1, torch.tensor([0, 1, 4, 5], device=boxes.device, dtype=torch.long))[:, :, 1]
- heights = bot - upper + 1
- assert torch.allclose(
- heights.permute(1, 0), heights[:, 0]
- ), f"Boxes must have be cube, while get different heights {heights}."
-
- depths = boxes[:, 4:, 2] - boxes[:, :4, 2] + 1
- assert torch.allclose(
- depths.permute(1, 0), depths[:, 0]
- ), f"Boxes must have be cube, while get different depths {depths}."
+ warnings.warn(
+ "`kornia.geometry.transforms.crop.crop2d.infer_box_shape3d` is deprecated and will be removed > 0.6.0. "
+ "Please use `kornia.geometry.bbox.infer_bbox_shape3d instead.`",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return _infer_bbox_shape3d(boxes)
def bbox_to_mask3d(boxes: torch.Tensor, size: Tuple[int, int, int]) -> torch.Tensor:
@@ -498,35 +482,13 @@ def bbox_to_mask3d(boxes: torch.Tensor, size: Tuple[int, int, int]) -> torch.Ten
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]]]]])
"""
- validate_bboxes3d(boxes)
- mask = torch.zeros((len(boxes), *size))
-
- mask_out = []
- # TODO: Looking for a vectorized way
- for m, box in zip(mask, boxes):
- m = m.index_fill(
- 0,
- torch.arange(box[0, 2].item(), box[4, 2].item() + 1, device=box.device, dtype=torch.long),
- torch.tensor(1, device=box.device, dtype=box.dtype),
- )
- m = m.index_fill(
- 1,
- torch.arange(box[1, 1].item(), box[2, 1].item() + 1, device=box.device, dtype=torch.long),
- torch.tensor(1, device=box.device, dtype=box.dtype),
- )
- m = m.index_fill(
- 2,
- torch.arange(box[0, 0].item(), box[1, 0].item() + 1, device=box.device, dtype=torch.long),
- torch.tensor(1, device=box.device, dtype=box.dtype),
- )
- m = m.unsqueeze(dim=0)
- m_out = torch.ones_like(m)
- m_out = m_out * (m == 1).all(dim=2, keepdim=True).all(dim=1, keepdim=True)
- m_out = m_out * (m == 1).all(dim=3, keepdim=True).all(dim=1, keepdim=True)
- m_out = m_out * (m == 1).all(dim=2, keepdim=True).all(dim=3, keepdim=True)
- mask_out.append(m_out)
-
- return torch.stack(mask_out, dim=0).float()
+ warnings.warn(
+ "`kornia.geometry.transforms.crop.crop2d.bbox_to_mask3d` is deprecated and will be removed > 0.6.0. "
+ "Please use `kornia.geometry.bbox.bbox_to_mask3d instead.`",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return _bbox_to_mask3d(boxes, size)
def bbox_generator3d(
@@ -582,41 +544,10 @@ def bbox_generator3d(
[43, 54, 65],
[ 3, 54, 65]]])
"""
- assert x_start.shape == y_start.shape == z_start.shape and x_start.dim() in [
- 0,
- 1,
- ], f"`x_start`, `y_start` and `z_start` must be a scalar or (B,). Got {x_start}, {y_start}, {z_start}."
- assert width.shape == height.shape == depth.shape and width.dim() in [
- 0,
- 1,
- ], f"`width`, `height` and `depth` must be a scalar or (B,). Got {width}, {height}, {depth}."
- assert x_start.dtype == y_start.dtype == z_start.dtype == width.dtype == height.dtype == depth.dtype, (
- "All tensors must be in the same dtype. "
- f"Got `x_start`({x_start.dtype}), `y_start`({x_start.dtype}), `z_start`({x_start.dtype}), "
- f"`width`({width.dtype}), `height`({height.dtype}) and `depth`({depth.dtype})."
+ warnings.warn(
+ "`kornia.geometry.transforms.crop.crop2d.bbox_generator3d` is deprecated and will be removed > 0.6.0. "
+ "Please use `kornia.geometry.bbox.bbox_generator3d instead.`",
+ DeprecationWarning,
+ stacklevel=2,
)
- assert x_start.device == y_start.device == z_start.device == width.device == height.device == depth.device, (
- "All tensors must be in the same device. "
- f"Got `x_start`({x_start.device}), `y_start`({x_start.device}), `z_start`({x_start.device}), "
- f"`width`({width.device}), `height`({height.device}) and `depth`({depth.device})."
- )
-
- # front
- bbox = torch.tensor(
- [[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]], device=x_start.device, dtype=x_start.dtype
- ).repeat(len(x_start), 1, 1)
-
- bbox[:, :, 0] += x_start.view(-1, 1)
- bbox[:, :, 1] += y_start.view(-1, 1)
- bbox[:, :, 2] += z_start.view(-1, 1)
- bbox[:, 1, 0] += width
- bbox[:, 2, 0] += width
- bbox[:, 2, 1] += height
- bbox[:, 3, 1] += height
-
- # back
- bbox_back = bbox.clone()
- bbox_back[:, :, -1] += depth.unsqueeze(dim=1).repeat(1, 4)
- bbox = torch.cat([bbox, bbox_back], dim=1)
-
- return bbox
+ return _bbox_generator3d(x_start, y_start, z_start, width, height, depth)
diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.py
index d38f8194b..6920291ce 100644
--- a/test/augmentation/test_container.py
+++ b/test/augmentation/test_container.py
@@ -4,7 +4,7 @@ import torch
import kornia
import kornia.augmentation as K
from kornia.constants import BorderType
-from kornia.geometry.transform import bbox_to_mask
+from kornia.geometry.bbox import bbox_to_mask
from kornia.testing import assert_close
diff --git a/test/geometry/test_bbox.py b/test/geometry/test_bbox.py
new file mode 100644
index 000000000..4c34f4c7f
--- /dev/null
+++ b/test/geometry/test_bbox.py
@@ -0,0 +1,245 @@
+import pytest
+import torch
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+import kornia
+import kornia.testing as utils
+from kornia.geometry.bbox import infer_bbox_shape, infer_bbox_shape3d, transform_bbox, validate_bbox, validate_bbox3d
+
+
+class TestBbox2D:
+ def test_smoke(self, device, dtype):
+
+ # Sample two points of the rectangle
+ points = torch.rand(1, 4, device=device, dtype=dtype)
+
+ # Fill acording missing points
+ bbox = torch.zeros(1, 4, 2, device=device, dtype=dtype)
+ bbox[0, 0] = points[0][:2]
+ bbox[0, 1, 0] = points[0][2]
+ bbox[0, 1, 1] = points[0][1]
+ bbox[0, 2] = points[0][2:]
+ bbox[0, 3, 0] = points[0][0]
+ bbox[0, 3, 1] = points[0][3]
+
+ # Validate
+ assert validate_bbox(bbox)
+
+ def test_bounding_boxes_dim_inferring(self, device, dtype):
+ boxes = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
+ h, w = infer_bbox_shape(boxes)
+ assert (h, w) == (2, 3)
+
+ def test_bounding_boxes_dim_inferring_batch(self, device, dtype):
+ boxes = torch.tensor(
+ [[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]], [[2.0, 2.0], [4.0, 2.0], [4.0, 3.0], [2.0, 3.0]]],
+ device=device,
+ dtype=dtype,
+ )
+ h, w = infer_bbox_shape(boxes)
+ assert (h.unique().item(), w.unique().item()) == (2, 3)
+
+ def test_gradcheck(self, device, dtype):
+ boxes = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
+ boxes = utils.tensor_to_gradcheck_var(boxes)
+ assert gradcheck(infer_bbox_shape, (boxes,), raise_exception=True)
+
+ def test_jit(self, device, dtype):
+ # Define script
+ op = infer_bbox_shape
+ op_script = torch.jit.script(op)
+ # Define input
+ boxes = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
+ # Run
+ expected = op(boxes)
+ actual = op_script(boxes)
+ # Compare
+ assert_allclose(actual, expected)
+
+
+class TestTransformBoxes2D:
+ def test_transform_boxes(self, device, dtype):
+
+ boxes = torch.tensor([[139.2640, 103.0150, 397.3120, 410.5225]], device=device, dtype=dtype)
+
+ expected = torch.tensor([[372.7360, 103.0150, 114.6880, 410.5225]], 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]]], device=device, dtype=dtype)
+
+ out = transform_bbox(trans_mat, boxes)
+ assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
+
+ def test_transform_multiple_boxes(self, device, dtype):
+
+ boxes = torch.tensor(
+ [
+ [139.2640, 103.0150, 397.3120, 410.5225],
+ [1.0240, 80.5547, 512.0000, 512.0000],
+ [165.2053, 262.1440, 510.6347, 508.9280],
+ [119.8080, 144.2067, 257.0240, 410.1292],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ boxes = boxes.repeat(2, 1, 1) # 2 x 4 x 4 two images 4 boxes each
+
+ expected = torch.tensor(
+ [
+ [
+ [372.7360, 103.0150, 114.6880, 410.5225],
+ [510.9760, 80.5547, 0.0000, 512.0000],
+ [346.7947, 262.1440, 1.3653, 508.9280],
+ [392.1920, 144.2067, 254.9760, 410.1292],
+ ],
+ [
+ [139.2640, 103.0150, 397.3120, 410.5225],
+ [1.0240, 80.5547, 512.0000, 512.0000],
+ [165.2053, 262.1440, 510.6347, 508.9280],
+ [119.8080, 144.2067, 257.0240, 410.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,
+ )
+
+ out = transform_bbox(trans_mat, boxes)
+ assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
+
+ def test_transform_boxes_wh(self, device, dtype):
+
+ boxes = torch.tensor(
+ [
+ [139.2640, 103.0150, 258.0480, 307.5075],
+ [1.0240, 80.5547, 510.9760, 431.4453],
+ [165.2053, 262.1440, 345.4293, 246.7840],
+ [119.8080, 144.2067, 137.2160, 265.9225],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ expected = torch.tensor(
+ [
+ [372.7360, 103.0150, -258.0480, 307.5075],
+ [510.9760, 80.5547, -510.9760, 431.4453],
+ [346.7947, 262.1440, -345.4293, 246.7840],
+ [392.1920, 144.2067, -137.2160, 265.9225],
+ ],
+ 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]]], device=device, dtype=dtype)
+
+ out = transform_bbox(trans_mat, boxes, mode='xywh')
+ assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
+
+ def test_gradcheck(self, device, dtype):
+
+ boxes = torch.tensor(
+ [
+ [139.2640, 103.0150, 258.0480, 307.5075],
+ [1.0240, 80.5547, 510.9760, 431.4453],
+ [165.2053, 262.1440, 345.4293, 246.7840],
+ [119.8080, 144.2067, 137.2160, 265.9225],
+ ],
+ 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]]], device=device, dtype=dtype)
+
+ trans_mat = utils.tensor_to_gradcheck_var(trans_mat)
+ boxes = utils.tensor_to_gradcheck_var(boxes)
+
+ assert gradcheck(transform_bbox, (trans_mat, boxes), raise_exception=True)
+
+ def test_jit(self, device, dtype):
+ boxes = torch.tensor([[139.2640, 103.0150, 258.0480, 307.5075]], 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]]], device=device, dtype=dtype)
+ args = (boxes, trans_mat)
+ op = kornia.geometry.transform_points
+ op_jit = torch.jit.script(op)
+ assert_allclose(op(*args), op_jit(*args))
+
+
+class TestBbox3D:
+ def test_smoke(self, device, dtype):
+ # Sample two points of the 3d rect
+ points = torch.rand(1, 6, device=device, dtype=dtype)
+
+ # Fill acording missing points
+ bbox = torch.zeros(1, 8, 3, device=device, dtype=dtype)
+ bbox[0, 0] = points[0][:3]
+ bbox[0, 1, 0] = points[0][3]
+ bbox[0, 1, 1] = points[0][1]
+ bbox[0, 1, 2] = points[0][2]
+ bbox[0, 2, 0] = points[0][3]
+ bbox[0, 2, 1] = points[0][4]
+ bbox[0, 2, 2] = points[0][2]
+ bbox[0, 3, 0] = points[0][0]
+ bbox[0, 3, 1] = points[0][4]
+ bbox[0, 3, 2] = points[0][2]
+ bbox[0, 4, 0] = points[0][0]
+ bbox[0, 4, 1] = points[0][1]
+ bbox[0, 4, 2] = points[0][5]
+ bbox[0, 5, 0] = points[0][3]
+ bbox[0, 5, 1] = points[0][1]
+ bbox[0, 5, 2] = points[0][5]
+ bbox[0, 6] = points[0][3:]
+ bbox[0, 7, 0] = points[0][0]
+ bbox[0, 7, 1] = points[0][4]
+ bbox[0, 7, 2] = points[0][5]
+
+ # Validate
+ assert validate_bbox3d(bbox)
+
+ def test_bounding_boxes_dim_inferring(self, device, dtype):
+ boxes = 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]],
+ [[3, 4, 5], [43, 4, 5], [43, 54, 5], [3, 54, 5], [3, 4, 65], [43, 4, 65], [43, 54, 65], [3, 54, 65]],
+ ],
+ device=device,
+ dtype=dtype,
+ ) # 2x8x3
+ d, h, w = infer_bbox_shape3d(boxes)
+
+ assert_allclose(d, torch.tensor([31.0, 61.0], device=device, dtype=dtype))
+ assert_allclose(h, torch.tensor([21.0, 51.0], device=device, dtype=dtype))
+ assert_allclose(w, torch.tensor([11.0, 41.0], device=device, dtype=dtype))
+
+ def test_gradcheck(self, device, dtype):
+ boxes = 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,
+ )
+ boxes = utils.tensor_to_gradcheck_var(boxes)
+ assert gradcheck(infer_bbox_shape3d, (boxes,), raise_exception=True)
+
+ def test_jit(self, device, dtype):
+ # Define script
+ op = infer_bbox_shape3d
+ op_script = torch.jit.script(op)
+
+ boxes = torch.tensor(
+ [[[0, 0, 1], [3, 0, 1], [3, 2, 1], [0, 2, 1], [0, 0, 3], [3, 0, 3], [3, 2, 3], [0, 2, 3]]],
+ device=device,
+ dtype=dtype,
+ ) # 1x8x3
+
+ actual = op_script(boxes)
+ expected = op(boxes)
+ assert_allclose(actual, expected)
diff --git a/test/geometry/transform/crop/test_crop2d.py b/test/geometry/transform/crop/test_crop2d.py
index dcb5778b0..b444f7d57 100644
--- a/test/geometry/transform/crop/test_crop2d.py
+++ b/test/geometry/transform/crop/test_crop2d.py
@@ -6,39 +6,6 @@ import kornia.testing as utils # test utils
from kornia.testing import assert_close
-class TestBoundingBoxInferring:
- def test_bounding_boxes_dim_inferring(self, device, dtype):
- boxes = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
-
- h, w = kornia.geometry.transform.crop.infer_box_shape(boxes)
- assert (h, w) == (2, 3)
-
- def test_bounding_boxes_dim_inferring_batch(self, device, dtype):
- boxes = torch.tensor(
- [[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]], [[2.0, 2.0], [4.0, 2.0], [4.0, 3.0], [2.0, 3.0]]],
- device=device,
- dtype=dtype,
- )
- h, w = kornia.geometry.transform.crop.infer_box_shape(boxes)
- assert (h.unique().item(), w.unique().item()) == (2, 3)
-
- def test_gradcheck(self, device, dtype):
- boxes = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
- boxes = utils.tensor_to_gradcheck_var(boxes)
- assert gradcheck(kornia.kornia.geometry.transform.crop.infer_box_shape, (boxes,), raise_exception=True)
-
- def test_jit(self, device, dtype):
- # Define script
- op = kornia.geometry.transform.crop.infer_box_shape
- op_script = torch.jit.script(op)
- # Define input
- boxes = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
-
- actual = op_script(boxes)
- expected = op(boxes)
- assert_close(actual, expected)
-
-
class TestCropAndResize:
def test_align_corners_true(self, device, dtype):
inp = torch.tensor(
diff --git a/test/geometry/transform/crop/test_crop3d.py b/test/geometry/transform/crop/test_crop3d.py
index 3c9200203..418205bfc 100644
--- a/test/geometry/transform/crop/test_crop3d.py
+++ b/test/geometry/transform/crop/test_crop3d.py
@@ -7,47 +7,6 @@ import kornia.testing as utils # test utils
from kornia.testing import assert_close
-class TestBoundingBoxInferring3D:
- def test_bounding_boxes_dim_inferring(self, device, dtype):
- boxes = 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]],
- [[3, 4, 5], [43, 4, 5], [43, 54, 5], [3, 54, 5], [3, 4, 65], [43, 4, 65], [43, 54, 65], [3, 54, 65]],
- ],
- device=device,
- dtype=dtype,
- ) # 2x8x3
- d, h, w = kornia.geometry.transform.crop.infer_box_shape3d(boxes)
-
- assert_close(d, torch.tensor([31.0, 61.0], device=device, dtype=dtype))
- assert_close(h, torch.tensor([21.0, 51.0], device=device, dtype=dtype))
- assert_close(w, torch.tensor([11.0, 41.0], device=device, dtype=dtype))
-
- def test_gradcheck(self, device, dtype):
- boxes = 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,
- )
- boxes = utils.tensor_to_gradcheck_var(boxes)
- assert gradcheck(kornia.kornia.geometry.transform.crop.infer_box_shape3d, (boxes,), raise_exception=True)
-
- def test_jit(self, device, dtype):
- # Define script
- op = kornia.infer_box_shape3d
- op_script = torch.jit.script(op)
-
- boxes = torch.tensor(
- [[[0, 0, 1], [3, 0, 1], [3, 2, 1], [0, 2, 1], [0, 0, 3], [3, 0, 3], [3, 2, 3], [0, 2, 3]]],
- device=device,
- dtype=dtype,
- ) # 1x8x3
-
- actual = op_script(boxes)
- expected = op(boxes)
- assert_close(actual, expected)
-
-
class TestCropAndResize3D:
def test_crop(self, device, dtype):
inp = torch.arange(0.0, 64.0, device=device, dtype=dtype).view(1, 1, 4, 4, 4)