Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

implement crop_and_resize

edgarribadac14d9b7259
diff --git a/docs/source/geometric.rst b/docs/source/geometric.rst
index a5c6e20fb..e29697457 100644
--- a/docs/source/geometric.rst
+++ b/docs/source/geometric.rst
@@ -12,6 +12,7 @@ The functions in this section perform various geometrical transformations of 2D
.. autofunction:: remap
.. autofunction:: invert_affine_transform
.. autofunction:: center_crop
+.. autofunction:: crop_and_resize
.. autofunction:: affine
.. autofunction:: rotate
diff --git a/test/test_crop.py b/test/test_crop.py
index 27eb2d374..4ef78ece3 100644
--- a/test/test_crop.py
+++ b/test/test_crop.py
@@ -10,6 +10,144 @@ from torch.autograd import gradcheck
import utils # test utils
+class TestCropAndResize:
+ def test_crop(self):
+ inp = torch.tensor([[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]])
+
+ height, width = 2, 2
+ expected = torch.tensor([[
+ [6., 7.],
+ [10., 11.],
+ ]])
+
+ boxes = torch.tensor([[
+ [1., 1.],
+ [1., 2.],
+ [2., 1.],
+ [2., 2.],
+ ]]) # 1x4x2
+
+ patches = tgm.crop_and_resize(inp, boxes, (height, width))
+ assert_allclose(patches, expected)
+
+ def test_crop_batch(self):
+ inp = torch.tensor([[[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]], [[
+ [1., 5., 9., 13.],
+ [2., 6., 10., 14.],
+ [3., 7., 11., 15.],
+ [4., 8., 12., 16.],
+ ]]])
+
+ height, width = 2, 2
+ expected = torch.tensor([[[
+ [6., 7.],
+ [10., 11.],
+ ]], [[
+ [11., 15.],
+ [12., 16.],
+ ]]])
+
+ boxes = torch.tensor([[
+ [1., 1.],
+ [1., 2.],
+ [2., 1.],
+ [2., 2.],
+ ], [
+ [2., 2.],
+ [2., 3.],
+ [3., 2.],
+ [3., 3.],
+ ]]) # 2x4x2
+
+ patches = tgm.crop_and_resize(inp, boxes, (height, width))
+ assert_allclose(patches, expected)
+
+ def test_crop_batch_broadcast(self):
+ inp = torch.tensor([[[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]], [[
+ [1., 5., 9., 13.],
+ [2., 6., 10., 14.],
+ [3., 7., 11., 15.],
+ [4., 8., 12., 16.],
+ ]]])
+
+ height, width = 2, 2
+ expected = torch.tensor([[[
+ [6., 7.],
+ [10., 11.],
+ ]], [[
+ [6., 10.],
+ [7., 11.],
+ ]]])
+
+ boxes = torch.tensor([[
+ [1., 1.],
+ [1., 2.],
+ [2., 1.],
+ [2., 2.],
+ ]]) # 1x4x2
+
+ patches = tgm.crop_and_resize(inp, boxes, (height, width))
+ assert_allclose(patches, expected)
+
+ def test_gradcheck(self):
+ batch_size, channels, height, width = 1, 2, 5, 4
+ img = torch.rand(batch_size, channels, height, width)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+
+ boxes = torch.tensor([[
+ [1., 1.],
+ [1., 2.],
+ [2., 1.],
+ [2., 2.],
+ ]]) # 1x4x2
+ boxes = utils.tensor_to_gradcheck_var(
+ boxes, requires_grad=False) # to var
+
+ crop_height, crop_width = 4, 2
+ assert gradcheck(tgm.crop_and_resize,
+ (img, boxes, (crop_height, crop_width),),
+ raise_exception=True)
+
+ def test_jit(self):
+ @torch.jit.script
+ def op_script(input: torch.Tensor,
+ boxes: torch.Tensor,
+ size: Tuple[int, int]) -> torch.Tensor:
+ return tgm.crop_and_resize(input, boxes, size)
+ img = torch.tensor([[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]])
+ boxes = torch.tensor([[
+ [1., 1.],
+ [1., 2.],
+ [2., 1.],
+ [2., 2.],
+ ]]) # 1x4x2
+
+ crop_height, crop_width = 4, 2
+ actual = op_script(img, boxes, (crop_height, crop_width))
+ expected = tgm.crop_and_resize(img, boxes, (crop_height, crop_width))
+ assert_allclose(actual, expected)
+
+
class TestCenterCrop:
def test_center_crop_h2_w4(self):
inp = torch.tensor([[
diff --git a/torchgeometry/__init__.py b/torchgeometry/__init__.py
index a8314c08b..ad921d6f6 100644
--- a/torchgeometry/__init__.py
+++ b/torchgeometry/__init__.py
@@ -23,4 +23,4 @@ from .core.transformations import *
from .core.affine import (
affine, rotate, translate, scale, shear, Rotate, Translate, Scale, Shear
)
-from .core.crop import center_crop
+from .core.crop import center_crop, crop_and_resize
diff --git a/torchgeometry/core/__init__.py b/torchgeometry/core/__init__.py
index 07d463533..a0e766f52 100644
--- a/torchgeometry/core/__init__.py
+++ b/torchgeometry/core/__init__.py
@@ -7,4 +7,4 @@ from .transformations import *
from .affine import (
affine, rotate, translate, scale, shear, Rotate, Translate, Scale, Shear
)
-from .crop import center_crop
+from .crop import center_crop, crop_and_resize
diff --git a/torchgeometry/core/crop.py b/torchgeometry/core/crop.py
index d76d6317c..50b344be8 100644
--- a/torchgeometry/core/crop.py
+++ b/torchgeometry/core/crop.py
@@ -1,4 +1,4 @@
-from typing import Tuple, Union
+from typing import Tuple
import torch
@@ -6,6 +6,93 @@ from torchgeometry.core.imgwarp import warp_perspective
from torchgeometry.core.imgwarp import get_perspective_transform
+def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor,
+ size: Tuple[int, int]) -> torch.Tensor:
+ r"""Extracts crops from the input tensor and resizes them.
+
+ Args:
+ tensor (torch.Tensor): the reference tensor of shape BxCxHxW.
+ 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 order: top-left,
+ top-right, bottom-left and bottom-right. The coordinates order must
+ be in y, x respectively.
+ size (Tuple[int, int]): a tuple with the height and width that will be
+ used to resize the extracted patches.
+
+ Returns:
+ torch.Tensor: tensor containing the patches with shape BxN1xN2
+
+ Example:
+ >>> input = torch.tensor([[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]])
+ >>> boxes = torch.tensor([[
+ [1., 1.],
+ [1., 2.],
+ [2., 1.],
+ [2., 2.],
+ ]]) # 1x4x2
+ >>> tgm.crop_and_resize(input, boxes, (2, 2))
+ tensor([[[ 6.0000, 7.0000],
+ [ 10.0000, 11.0000]]])
+ """
+ if not torch.is_tensor(tensor):
+ raise TypeError("Input tensor type is not a torch.Tensor. Got {}"
+ .format(type(tensor)))
+ if not torch.is_tensor(boxes):
+ raise TypeError("Input boxes type is not a torch.Tensor. Got {}"
+ .format(type(boxes)))
+ if not len(tensor.shape) in (3, 4,):
+ raise ValueError("Input tensor must be in the shape of CxHxW or "
+ "BxCxHxW. Got {}".format(tensor.shape))
+ if not isinstance(size, (tuple, list,)) and len(size) == 2:
+ raise ValueError("Input size must be a tuple/list of length 2. Got {}"
+ .format(size))
+ # unpack input data
+ dst_h: torch.Tensor = torch.tensor(size[0])
+ dst_w: torch.Tensor = torch.tensor(size[1])
+
+ # [y, x] origin
+ # top-left, top-right, bottom-left, bottom-right
+ points_src: torch.Tensor = boxes.to(
+ tensor.device).to(tensor.dtype)
+
+ # [y, x] destination
+ # top-left, top-right, bottom-left, bottom-right
+ points_dst: torch.Tensor = torch.tensor([[
+ [0, 0],
+ [0, dst_w - 1],
+ [dst_h - 1, 0],
+ [dst_h - 1, dst_w - 1],
+ ]]).repeat(points_src.shape[0], 1, 1).to(
+ tensor.device).to(tensor.dtype)
+
+ # warping needs data in the shape of BCHW
+ is_unbatched: bool = tensor.ndimension() == 3
+ if is_unbatched:
+ tensor = torch.unsqueeze(tensor, dim=0)
+
+ # compute transformation between points and warp
+ dst_trans_src: torch.Tensor = get_perspective_transform(
+ points_src, points_dst)
+
+ # simulate broadcasting
+ dst_trans_src = dst_trans_src.expand(tensor.shape[0], -1, -1)
+
+ patches: torch.Tensor = warp_perspective(
+ tensor, dst_trans_src, (dst_h, dst_w))
+
+ # return in the original shape
+ if is_unbatched:
+ patches = torch.squeeze(patches, dim=0)
+
+ return patches
+
+
def center_crop(tensor: torch.Tensor, size: Tuple[int, int]) -> torch.Tensor:
r"""Crops the given tensor at the center.