π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
feat(geometry): add optional support for image shape mismatch (#3600)
Ayushi Jain7dfd67ee0fbc
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.pyindex 9f14b8d26..1fde5f413 100644--- a/kornia/geometry/transform/image_registrator.py+++ b/kornia/geometry/transform/image_registrator.py@@ -168,6 +168,7 @@ class ImageRegistrator(nn.Module):num_iterations: int = 100,tolerance: float = 1e-4,warper: Optional[Type[BaseWarper]] = None,+ allow_shape_mismatch: bool = False,) -> None:super().__init__()self.known_models = ["homography", "similarity", "translation", "scale", "rotation"]@@ -201,6 +202,7 @@ class ImageRegistrator(nn.Module):self.loss_fn = loss_fnself.num_iterations = num_iterationsself.tolerance = tolerance+ self.allow_shape_mismatch = allow_shape_mismatchdef get_single_level_loss(self, img_src: torch.Tensor, img_dst: torch.Tensor, transform_model: torch.Tensor@@ -248,6 +250,18 @@ class ImageRegistrator(nn.Module):"""self.reset_model()+ if src_img.shape != dst_img.shape:+ if not self.allow_shape_mismatch:+ raise ValueError(+ f"Cannot register images of different shapes {src_img.shape} {dst_img.shape}. "+ "Consider setting `allow_shape_mismatch = True`"+ )+ src_img = F.interpolate(+ src_img,+ size=dst_img.shape[-2:],+ mode="bilinear",+ align_corners=False,+ )# ToDo: better parameter passing to optimizer_opt_args: Dict[str, Any] = {}_opt_args["lr"] = self.lrdiff --git a/tests/geometry/transform/test_image_registrator.py b/tests/geometry/transform/test_image_registrator.pyindex c05044933..3fe5bf377 100644--- a/tests/geometry/transform/test_image_registrator.py+++ b/tests/geometry/transform/test_image_registrator.py@@ -122,3 +122,22 @@ class TestImageRegistrator(BaseTester):# and transformation is quite significant, so# 15 px reprojection error is not super hugeself.assert_close(bbox_in_2_gt, bbox_in_2_gt_est, atol=15, rtol=0.1)++ def test_register_with_shape_mismatch(self, device):+ img1 = torch.rand(1, 1, 64, 64, device=device)+ img2 = torch.rand(1, 1, 32, 32, device=device)++ registrator = ImageRegistrator("similarity", allow_shape_mismatch=True)++ out = registrator.register(img1, img2)++ assert out is not None++ def test_register_shape_mismatch_raises(self, device):+ img1 = torch.rand(1, 1, 64, 64, device=device)+ img2 = torch.rand(1, 1, 32, 32, device=device)++ registrator = ImageRegistrator("similarity", allow_shape_mismatch=False)++ with pytest.raises(ValueError):+ registrator.register(img1, img2)