Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): start center_crop and center_crop3d at an integer pixel (#6313)

Saksham Sharma60bde118524c
diff --git a/changelog.d/6313.fixed.md b/changelog.d/6313.fixed.md
new file mode 100644
index 000000000..bec7c7f55
--- /dev/null
+++ b/changelog.d/6313.fixed.md
@@ -0,0 +1 @@
+`kornia.geometry.transform.center_crop` and `center_crop3d` now start the crop at the integer pixel `int(src / 2 - dst / 2)`, as `CenterCrop2D`, `K.CenterCrop` and `K.CenterCrop3D` do, so they return a sub-image of the input (for `center_crop3d`, with its default `align_corners=True`). With an odd margin they used to start half a pixel off the grid, so `bilinear` blended neighbouring pixels and `nearest` duplicated rows or columns instead of returning the centre slice. For a `size` larger than the input with an odd margin, the extra padding pixel is now at the bottom/right.
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index d882b50b2..67b31a589 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -167,6 +167,9 @@ def center_crop(
Convention:
- input: :math:`(B, C, H, W)` (strictly 4D β€” no unbatched ``(C, H, W)``/
``(H, W)`` input is accepted); ``size`` is ``(h, w)``
+ - offset: the crop starts at the integer pixel ``int(H / 2 - h / 2)`` (likewise for the width), as in
+ :class:`CenterCrop2D`, so the output is a sub-image of the input. With an odd margin the extra pixel is
+ left at the bottom/right; for a ``size`` larger than the input, the extra padding pixel goes there too.
Args:
input_tensor: the 2D image torch.Tensor with shape (B, C, H, W).
@@ -212,11 +215,12 @@ def center_crop(
src_h_half: float = src_h / 2
src_w_half: float = src_w / 2
- start_x: float = src_w_half - dst_w_half
- start_y: float = src_h_half - dst_h_half
+ # an integer start, as CenterCrop2D takes it: a fractional one would resample between pixels
+ start_x: int = int(src_w_half - dst_w_half)
+ start_y: int = int(src_h_half - dst_h_half)
- end_x: float = start_x + dst_w - 1
- end_y: float = start_y + dst_h - 1
+ end_x: int = start_x + dst_w - 1
+ end_y: int = start_y + dst_h - 1
# [y, x] origin
# top-left, top-right, bottom-right, bottom-left
diff --git a/kornia/geometry/transform/crop3d.py b/kornia/geometry/transform/crop3d.py
index 002f53d28..6b71d4e2d 100644
--- a/kornia/geometry/transform/crop3d.py
+++ b/kornia/geometry/transform/crop3d.py
@@ -146,6 +146,11 @@ def center_crop3d(
Convention:
- input: :math:`(B, C, D, H, W)`; ``size`` is ``(d, h, w)``
- align_corners: ``True`` by default
+ - offset: the crop starts at the integer voxel ``int(D / 2 - d / 2)`` (likewise for the height and width),
+ as in :class:`~kornia.augmentation.CenterCrop3D`, so with the default ``align_corners=True`` the output is a
+ sub-volume of the input. With an odd margin the extra voxel is left at the back/bottom/right.
+ ``align_corners=False`` resamples off the voxel grid even for an even margin (see
+ :func:`crop_and_resize3d`).
Args:
tensor: the 3D volume tensor with shape (B, C, D, H, W).
@@ -208,9 +213,10 @@ def center_crop3d(
src_h_half = src_h / 2
src_w_half = src_w / 2
- start_x = src_w_half - dst_w_half
- start_y = src_h_half - dst_h_half
- start_z = src_d_half - dst_d_half
+ # an integer start, as CenterCrop3D takes it: a fractional one would resample between voxels
+ start_x = int(src_w_half - dst_w_half)
+ start_y = int(src_h_half - dst_h_half)
+ start_z = int(src_d_half - dst_d_half)
end_x = start_x + dst_w - 1
end_y = start_y + dst_h - 1
diff --git a/tests/geometry/transform/test_crop2d.py b/tests/geometry/transform/test_crop2d.py
index 4a2b179f8..f307af7eb 100644
--- a/tests/geometry/transform/test_crop2d.py
+++ b/tests/geometry/transform/test_crop2d.py
@@ -322,17 +322,55 @@ class TestCenterCrop(BaseTester):
kornia.geometry.transform.CenterCrop2D(size, cropping_mode="resample")(inp), expected, atol=1e-4, rtol=1e-4
)
+ @pytest.mark.parametrize("align_corners", [True, False])
+ @pytest.mark.parametrize("mode", ["bilinear", "nearest"])
+ @pytest.mark.parametrize(
+ "size, top, left",
+ [((3, 4), 0, 0), ((2, 2), 1, 1), ((1, 3), 1, 1), ((4, 2), 0, 1)],
+ )
+ def test_convention_center_crop_odd_margin_returns_a_sub_image_6290(
+ self, size, top, left, mode, align_corners, device, dtype
+ ):
+ # A 4x5 image with an odd margin on at least one axis. The crop starts at int(src / 2 - dst / 2), as in
+ # CenterCrop2D, and leaves the extra pixel at the bottom/right. A fractional start resampled between
+ # pixels instead, so bilinear blended neighbours and nearest picked an arbitrary side. In 2D both
+ # align_corners conventions resolve the pixel-coordinate box to the same pixel centres (#3904).
+ if mode == "bilinear" and not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("bilinear 2D grid_sample is unavailable for this device and dtype")
+ inp = torch.arange(20.0, device=device, dtype=dtype).view(1, 1, 4, 5) ** 2
+ expected = inp[..., top : top + size[0], left : left + size[1]]
+
+ out = kornia.geometry.transform.center_crop(inp, size, mode=mode, align_corners=align_corners)
+ self.assert_close(out, expected, atol=1e-4, rtol=1e-4)
+ self.assert_close(out, kornia.geometry.transform.CenterCrop2D(size)(inp), atol=1e-4, rtol=1e-4)
+
+ @pytest.mark.parametrize("align_corners", [True, False])
+ def test_convention_center_crop_oversized_odd_margin_pads_bottom_right_6290(self, align_corners, device, dtype):
+ # A size larger than the input pads. With a negative odd margin the start is int(src / 2 - dst / 2), not
+ # (src - dst) // 2: -1 rather than -2 on the width (margin -3) and 0 rather than -1 on the height (margin
+ # -1). So the extra padding pixel is at the bottom/right, as in CenterCrop2D(cropping_mode="resample").
+ if not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("bilinear 2D grid_sample is unavailable for this device and dtype")
+ inp = torch.tensor([[[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [[[[0.0, 1.0, 2.0, 3.0, 0.0, 0.0], [0.0, 4.0, 5.0, 6.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]]],
+ device=device,
+ dtype=dtype,
+ )
+
+ out = kornia.geometry.transform.center_crop(inp, (3, 6), align_corners=align_corners)
+ self.assert_close(out, expected, atol=1e-4, rtol=1e-4)
+ resample = kornia.geometry.transform.CenterCrop2D((3, 6), align_corners=align_corners, cropping_mode="resample")
+ self.assert_close(out, resample(inp), atol=1e-4, rtol=1e-4)
+
def test_center_crop_forwards_mode_padding_mode_and_align_corners(self, device, dtype):
- # center_crop hands mode, padding_mode and align_corners on to the warp; each one changes this output.
- # A 2-wide crop of a 5-wide image starts at pixel 1.5, so bilinear averages four neighbours while
- # nearest returns one of them.
+ # center_crop hands mode, padding_mode and align_corners on to the warp. The crop is a whole-pixel
+ # translation, so mode does not change an in-bounds crop: both modes return the same slice.
if not supports_bilinear_2d_grid_sample(device, dtype):
pytest.skip("bilinear 2D grid_sample is unavailable for this device and dtype")
inp = (torch.arange(25, device=device, dtype=dtype) ** 2).view(1, 1, 5, 5)
- bilinear = (inp[..., 1:3, 1:3] + inp[..., 1:3, 2:4] + inp[..., 2:4, 1:3] + inp[..., 2:4, 2:4]) / 4
- self.assert_close(kornia.geometry.transform.center_crop(inp, (2, 2)), bilinear)
- nearest = kornia.geometry.transform.center_crop(inp, (2, 2), mode="nearest")
- assert torch.isin(nearest, inp).all()
+ self.assert_close(kornia.geometry.transform.center_crop(inp, (2, 2)), inp[..., 1:3, 1:3])
+ self.assert_close(kornia.geometry.transform.center_crop(inp, (2, 2), mode="nearest"), inp[..., 1:3, 1:3])
# A 4x4 crop of a 2x2 image samples pixels -1..2, outside the image on every side.
small = torch.tensor([[[[1.0, 2.0], [3.0, 4.0]]]], device=device, dtype=dtype)
diff --git a/tests/geometry/transform/test_crop3d.py b/tests/geometry/transform/test_crop3d.py
index 91c444f9f..b939debf1 100644
--- a/tests/geometry/transform/test_crop3d.py
+++ b/tests/geometry/transform/test_crop3d.py
@@ -136,6 +136,24 @@ class TestCenterCrop3D(BaseTester):
out_crop = kornia.geometry.transform.center_crop3d(inp, crop_size, align_corners=True)
self.assert_close(out_crop, expected, rtol=1e-4, atol=1e-4)
+ @pytest.mark.parametrize(
+ "shape, size, start",
+ [
+ ((3, 4, 5), (2, 3, 4), (0, 0, 0)),
+ ((3, 4, 5), (2, 2, 2), (0, 1, 1)),
+ ((5, 4, 6), (2, 3, 3), (1, 0, 1)),
+ ],
+ )
+ def test_convention_center_crop3d_odd_margin_returns_a_sub_volume_6290(self, shape, size, start, device, dtype):
+ # Odd margins on every axis. The crop starts at int(src / 2 - dst / 2), as in CenterCrop3D, and leaves the
+ # extra voxel at the back/bottom/right, instead of resampling between voxels. The default align_corners=True
+ # is the setting that reproduces an integer-voxel slice (see crop_and_resize3d's convention block).
+ inp = torch.arange(float(shape[0] * shape[1] * shape[2]), device=device, dtype=dtype).view(1, 1, *shape) ** 2
+ z, y, x = start
+ expected = inp[..., z : z + size[0], y : y + size[1], x : x + size[2]]
+
+ self.assert_close(kornia.geometry.transform.center_crop3d(inp, size), expected, atol=1e-4, rtol=1e-4)
+
def test_gradcheck(self, device):
img = torch.arange(0.0, 343.0, device=device, dtype=torch.float64).view(1, 1, 7, 7, 7)