Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

implement center_crop

edgarriba764310eb6c15
diff --git a/docs/source/geometric.rst b/docs/source/geometric.rst
index ddd666cbc..a5c6e20fb 100644
--- a/docs/source/geometric.rst
+++ b/docs/source/geometric.rst
@@ -11,6 +11,7 @@ The functions in this section perform various geometrical transformations of 2D
.. autofunction:: get_rotation_matrix2d
.. autofunction:: remap
.. autofunction:: invert_affine_transform
+.. autofunction:: center_crop
.. autofunction:: affine
.. autofunction:: rotate
diff --git a/mypy_files.txt b/mypy_files.txt
index 64d47bf8d..f1d1b4811 100644
--- a/mypy_files.txt
+++ b/mypy_files.txt
@@ -2,6 +2,8 @@ torchgeometry/core/homography_warper.py
torchgeometry/core/depth_warper.py
torchgeometry/core/pinhole.py
torchgeometry/core/imgwarp.py
+torchgeometry/core/crop.py
+torchgeometry/core/affine.py
torchgeometry/image/gaussian.py
torchgeometry/image/color.py
torchgeometry/image/laplacian.py
diff --git a/test/test_crop.py b/test/test_crop.py
new file mode 100644
index 000000000..27eb2d374
--- /dev/null
+++ b/test/test_crop.py
@@ -0,0 +1,124 @@
+from typing import Tuple
+
+import pytest
+
+import torch
+import torchgeometry as tgm
+from torch.testing import assert_allclose
+from torch.autograd import gradcheck
+
+import utils # test utils
+
+
+class TestCenterCrop:
+ def test_center_crop_h2_w4(self):
+ inp = torch.tensor([[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]])
+
+ height, width = 2, 4
+ expected = torch.tensor([[
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ ]])
+
+ out_crop = tgm.center_crop(inp, (height, width))
+ assert_allclose(out_crop, expected)
+
+ def test_center_crop_h4_w2(self):
+ inp = torch.tensor([[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]])
+
+ height, width = 4, 2
+ expected = torch.tensor([[
+ [2., 3.],
+ [6., 7.],
+ [10., 11.],
+ [14., 15.],
+ ]])
+
+ out_crop = tgm.center_crop(inp, (height, width))
+ assert_allclose(out_crop, expected)
+
+ def test_center_crop_h4_w2_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 = 4, 2
+ expected = torch.tensor([[
+ [2., 3.],
+ [6., 7.],
+ [10., 11.],
+ [14., 15.],
+ ], [
+ [5., 9.],
+ [6., 10.],
+ [7., 11.],
+ [8., 12.],
+ ]])
+
+ out_crop = tgm.center_crop(inp, (height, width))
+ assert_allclose(out_crop, 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
+
+ crop_height, crop_width = 4, 2
+ assert gradcheck(tgm.center_crop, (img, (crop_height, crop_width),),
+ raise_exception=True)
+
+ def test_jit(self):
+ @torch.jit.script
+ def op_script(input: torch.Tensor,
+ size: Tuple[int, int]) -> torch.Tensor:
+ return tgm.center_crop(input, size)
+ batch_size, channels, height, width = 1, 2, 5, 4
+ img = torch.ones(batch_size, channels, height, width)
+
+ crop_height, crop_width = 4, 2
+ actual = op_script(img, (crop_height, crop_width))
+ expected = tgm.center_crop(img, (crop_height, crop_width))
+ assert_allclose(actual, expected)
+
+ def test_jit_trace(self):
+ @torch.jit.script
+ def op_script(input: torch.Tensor,
+ size: Tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
+ return tgm.center_crop(input, size)
+ # 1. Trace op
+ batch_size, channels, height, width = 1, 2, 5, 4
+ img = torch.ones(batch_size, channels, height, width)
+
+ crop_height, crop_width = 4, 2
+ op_trace = torch.jit.trace(
+ op_script,
+ (img, (torch.tensor(crop_height), torch.tensor(crop_width))))
+
+ # 2. Generate new input
+ batch_size, channels, height, width = 2, 1, 6, 3
+ img = torch.ones(batch_size, channels, height, width)
+
+ # 3. Evaluate
+ crop_height, crop_width = 2, 3
+ actual = op_trace(
+ img, (torch.tensor(crop_height), torch.tensor(crop_width)))
+ expected = tgm.center_crop(img, (crop_height, crop_width))
+ assert_allclose(actual, expected)
diff --git a/torchgeometry/__init__.py b/torchgeometry/__init__.py
index fffb9f83c..a8314c08b 100644
--- a/torchgeometry/__init__.py
+++ b/torchgeometry/__init__.py
@@ -23,3 +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
diff --git a/torchgeometry/core/__init__.py b/torchgeometry/core/__init__.py
index 910b95f62..07d463533 100644
--- a/torchgeometry/core/__init__.py
+++ b/torchgeometry/core/__init__.py
@@ -7,3 +7,4 @@ from .transformations import *
from .affine import (
affine, rotate, translate, scale, shear, Rotate, Translate, Scale, Shear
)
+from .crop import center_crop
diff --git a/torchgeometry/core/crop.py b/torchgeometry/core/crop.py
new file mode 100644
index 000000000..d76d6317c
--- /dev/null
+++ b/torchgeometry/core/crop.py
@@ -0,0 +1,94 @@
+from typing import Tuple, Union
+
+import torch
+
+from torchgeometry.core.imgwarp import warp_perspective
+from torchgeometry.core.imgwarp import get_perspective_transform
+
+
+def center_crop(tensor: torch.Tensor, size: Tuple[int, int]) -> torch.Tensor:
+ r"""Crops the given tensor at the center.
+
+ Args:
+ tensor (torch.Tensor): the input tensor with shape (C, H, W) or
+ (B, C, H, W).
+ size (Tuple[int, int]): a tuple with the expected height and width
+ of the output patch.
+
+ Returns:
+ torch.Tensor: the output tensor with patches.
+
+ Examples:
+ >>> input = torch.tensor([[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]])
+ >>> tgm.center_crop(input, (2, 4))
+ tensor([[[ 5.0000, 6.0000, 7.0000, 8.0000],
+ [ 9.0000, 10.0000, 11.0000, 12.0000]]])
+ """
+ if not torch.is_tensor(tensor):
+ raise TypeError("Input tensor type is not a torch.Tensor. Got {}"
+ .format(type(tensor)))
+ 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 sizes
+ dst_h: torch.Tensor = torch.tensor(size[0])
+ dst_w: torch.Tensor = torch.tensor(size[1])
+ src_h: torch.Tensor = torch.tensor(tensor.shape[-2])
+ src_w: torch.Tensor = torch.tensor(tensor.shape[-1])
+
+ # compute start/end offsets
+ dst_h_half: torch.Tensor = dst_h / 2
+ dst_w_half: torch.Tensor = dst_w / 2
+ src_h_half: torch.Tensor = src_h / 2
+ src_w_half: torch.Tensor = src_w / 2
+
+ start_x: torch.Tensor = src_h_half - dst_h_half
+ start_y: torch.Tensor = src_w_half - dst_w_half
+
+ end_x: torch.Tensor = start_x + dst_w - 1
+ end_y: torch.Tensor = start_y + dst_h - 1
+
+ # [y, x] origin
+ # top-left, top-right, bottom-left, bottom-right
+ points_src: torch.Tensor = torch.tensor([[
+ [start_y, start_x],
+ [start_y, end_x],
+ [end_y, start_x],
+ [end_y, end_x],
+ ]]).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],
+ ]]).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)
+ dst_trans_src = dst_trans_src.repeat(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