Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add Image Stitching API (#1358)

Jian Shi38177ce1ea3b
diff --git a/docs/source/applications/image_stitching.rst b/docs/source/applications/image_stitching.rst
new file mode 100644
index 000000000..7cc275591
--- /dev/null
+++ b/docs/source/applications/image_stitching.rst
@@ -0,0 +1,18 @@
+Image Stitching
+============================
+
+Image stitching is the process of combining multiple images with overlapping fields of view to produce a segmented panorama. Here, we provide :py:class:`~kornia.contrib.ImageStitcher` to easily stitch a number of images.
+
+.. image:: https://raw.githubusercontent.com/kornia/data/main/matching/stitch_before.png
+
+.. code:: python
+
+ from kornia.contrib import ImageStitcher
+
+ matcher = KF.LoFTR(pretrained='outdoor')
+ IS = ImageStitcher(matcher, estimator='ransac').cuda()
+ # NOTE: it would require a large CPU memory if many images.
+ with torch.no_grad():
+ out = IS(*imgs)
+
+.. image:: https://raw.githubusercontent.com/kornia/data/main/matching/stitch_after.png
diff --git a/docs/source/index.rst b/docs/source/index.rst
index a09be37fe..6f0ed4c1f 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -57,6 +57,7 @@ Join the community
applications/image_augmentations
applications/image_classification
applications/image_matching
+ applications/image_stitching
applications/image_registration
applications/semantic_segmentation
applications/video_deblur
diff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.py
index 128af6383..dff4055e3 100644
--- a/kornia/contrib/__init__.py
+++ b/kornia/contrib/__init__.py
@@ -6,6 +6,7 @@ from kornia.contrib.extract_patches import (
extract_tensor_patches,
ExtractTensorPatches,
)
+from kornia.contrib.image_stitching import ImageStitcher
from kornia.contrib.lambda_module import Lambda
from kornia.contrib.vit import VisionTransformer
from kornia.contrib.vit_mobile import MobileViT
@@ -19,5 +20,6 @@ __all__ = [
"VisionTransformer",
"MobileViT",
"ClassificationHead",
- "Lambda"
+ "Lambda",
+ "ImageStitcher",
]
diff --git a/kornia/contrib/image_stitching.py b/kornia/contrib/image_stitching.py
new file mode 100644
index 000000000..b3614f222
--- /dev/null
+++ b/kornia/contrib/image_stitching.py
@@ -0,0 +1,136 @@
+from typing import Dict, List, Optional, Tuple
+
+import torch
+import torch.nn as nn
+
+import kornia as K
+
+__all__ = ["ImageStitcher"]
+
+
+class ImageStitcher(nn.Module):
+ """Stitch two images with overlapping fields of view.
+
+ Args:
+ matcher: image feature matching module.
+ estimator: method to compute homography, either "vanilla" or "ransac".
+ "ransac" is slower with a better accuracy.
+ blending_method: method to blend two images together.
+ Only "naive" is currently supported.
+
+ Note:
+ Current implementation requires strict image ordering from left to right.
+
+ .. code-block:: python
+
+ IS = ImageStitcher(KF.LoFTR(pretrained='outdoor'), estimator='ransac').cuda()
+ # Compute the stitched result with less GPU memory cost.
+ with torch.inference_mode():
+ out = IS(img_left, img_right)
+ # Show the result
+ plt.imshow(K.tensor_to_image(out))
+ """
+
+ def __init__(
+ self, matcher: nn.Module, estimator: str = 'ransac', blending_method: str = "naive",
+ ) -> None:
+ super().__init__()
+ self.matcher = matcher
+ self.estimator = estimator
+ self.blending_method = blending_method
+ if estimator not in ['ransac', 'vanilla']:
+ raise NotImplementedError(f"Unsupported estimator {estimator}. Use ‘ransac’ or ‘vanilla’ instead.")
+ if estimator == "ransac":
+ self.ransac = K.geometry.RANSAC('homography')
+
+ def _estimate_homography(self, keypoints1: torch.Tensor, keypoints2: torch.Tensor) -> torch.Tensor:
+ """Estimate homography by the matched keypoints.
+
+ Args:
+ keypoints1: matched keypoint set from an image, shaped as :math:`(N, 2)`.
+ keypoints2: matched keypoint set from the other image, shaped as :math:`(N, 2)`.
+ """
+ homo: torch.Tensor
+ if self.estimator == "vanilla":
+ homo = K.find_homography_dlt_iterated(
+ keypoints2[None],
+ keypoints1[None],
+ torch.ones_like(keypoints1[None, :, 0])
+ )
+ elif self.estimator == "ransac":
+ homo, _ = self.ransac(keypoints2, keypoints1)
+ homo = homo[None]
+ else:
+ raise NotImplementedError(f"Unsupported estimator {self.estimator}. Use ‘ransac’ or ‘vanilla’ instead.")
+ return homo
+
+ def estimate_transform(self, **kwargs) -> torch.Tensor:
+ """Compute the corresponding homography."""
+ homos: List[torch.Tensor] = []
+ kp1, kp2, idx = kwargs['keypoints0'], kwargs['keypoints1'], kwargs['batch_indexes']
+ for i in range(len(idx.unique())):
+ homos.append(self._estimate_homography(kp1[idx == i], kp2[idx == i]))
+ if len(homos) == 0:
+ raise RuntimeError("Compute homography failed. No matched keypoints found.")
+ return torch.cat(homos)
+
+ def blend_image(self, src_img: torch.Tensor, dst_img: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
+ """Blend two images together."""
+ out: torch.Tensor
+ if self.blending_method == "naive":
+ out = torch.where(mask == 1, src_img, dst_img)
+ else:
+ raise NotImplementedError(f"Unsupported blending method {self.blending_method}. Use ‘naive’.")
+ return out
+
+ def preprocess(self, image_1: torch.Tensor, image_2: torch.Tensor) -> Dict[str, torch.Tensor]:
+ """Preprocess input to the required format."""
+ # TODO: probably perform histogram matching here.
+ if isinstance(self.matcher, K.feature.LoFTR):
+ input_dict: Dict[str, torch.Tensor] = { # LofTR works on grayscale images only
+ "image0": K.color.rgb_to_grayscale(image_1),
+ "image1": K.color.rgb_to_grayscale(image_2)
+ }
+ else:
+ raise NotImplementedError(f"The preprocessor for {self.matcher} has not been implemented.")
+ return input_dict
+
+ def postprocess(self, image: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
+ # NOTE: assumes no batch mode. This method keeps all valid regions after stitching.
+ mask_: torch.Tensor = mask.sum((0, 1))
+ index: int = int(mask_.bool().any(0).long().argmin().item())
+ if index == 0: # If no redundant space
+ return image
+ return image[..., :index]
+
+ def on_matcher(self, data) -> dict:
+ return self.matcher(data)
+
+ def stitch_pair(
+ self, images_left: torch.Tensor, images_right: torch.Tensor,
+ mask_left: Optional[torch.Tensor] = None, mask_right: Optional[torch.Tensor] = None
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ # Compute the transformed images
+ input_dict: Dict[str, torch.Tensor] = self.preprocess(images_left, images_right)
+ out_shape: Tuple[int, int] = (images_left.shape[-2], images_left.shape[-1] + images_right.shape[-1])
+ correspondences: dict = self.on_matcher(input_dict)
+ homo: torch.Tensor = self.estimate_transform(**correspondences)
+ src_img = K.geometry.warp_perspective(images_right, homo, out_shape)
+ dst_img = torch.cat([images_left, torch.zeros_like(images_right)], dim=-1)
+
+ # Compute the transformed masks
+ if mask_left is None:
+ mask_left = torch.ones_like(images_left)
+ if mask_right is None:
+ mask_right = torch.ones_like(images_right)
+ # 'nearest' to ensure no floating points in the mask
+ src_mask = K.geometry.warp_perspective(mask_right, homo, out_shape, mode='nearest')
+ dst_mask = torch.cat([mask_left, torch.zeros_like(mask_right)], dim=-1)
+ return self.blend_image(src_img, dst_img, src_mask), (dst_mask + src_mask).bool().to(src_mask.dtype)
+
+ def forward(self, *imgs: torch.Tensor) -> torch.Tensor:
+ img_out = imgs[0]
+ mask_left = torch.ones_like(img_out)
+ for i in range(len(imgs) - 1):
+ img_out, mask_left = self.stitch_pair(img_out, imgs[i + 1], mask_left)
+ return self.postprocess(img_out, mask_left)
diff --git a/test/test_contrib.py b/test/test_contrib.py
index 572fad27c..b70fad89f 100644
--- a/test/test_contrib.py
+++ b/test/test_contrib.py
@@ -1,3 +1,5 @@
+from unittest.mock import patch, PropertyMock
+
import pytest
import torch
from torch.autograd import gradcheck
@@ -334,3 +336,43 @@ class TestLambdaModule:
img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
func = kornia.bgr_to_grayscale
assert gradcheck(kornia.contrib.Lambda(func), (img,), raise_exception=True)
+
+
+class TestImageStitcher:
+
+ @pytest.mark.parametrize("estimator", ['ransac', 'vanilla'])
+ def test_smoke(self, estimator, device, dtype):
+ B, C, H, W = 1, 3, 224, 224
+ input1 = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ input2 = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ return_value = {
+ "keypoints0": torch.rand((15, 2), device=device, dtype=dtype),
+ "keypoints1": torch.rand((15, 2), device=device, dtype=dtype),
+ "confidence": torch.rand((15,), device=device, dtype=dtype),
+ "batch_indexes": torch.zeros((15,), device=device, dtype=dtype)
+ }
+ with patch(
+ 'kornia.contrib.ImageStitcher.on_matcher',
+ new_callable=PropertyMock, return_value=lambda x: return_value
+ ):
+ # NOTE: This will need to download the pretrained weights.
+ # To avoid that, we mock as below
+ matcher = kornia.feature.LoFTR(None)
+ stitcher = kornia.contrib.ImageStitcher(matcher, estimator=estimator).to(device=device, dtype=dtype)
+ out = stitcher(input1, input2)
+ assert out.shape[:-1] == torch.Size([1, 3, 224])
+ assert out.shape[-1] <= 448
+
+ def test_exception(self, device, dtype):
+ B, C, H, W = 1, 3, 224, 224
+ input1 = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ input2 = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ # NOTE: This will need to download the pretrained weights.
+ matcher = kornia.feature.LoFTR(None)
+
+ with pytest.raises(NotImplementedError):
+ stitcher = kornia.contrib.ImageStitcher(matcher, estimator='random').to(device=device, dtype=dtype)
+
+ stitcher = kornia.contrib.ImageStitcher(matcher).to(device=device, dtype=dtype)
+ with pytest.raises(RuntimeError):
+ stitcher(input1, input2)