image_stitching.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. # LICENSE HEADER MANAGED BY add-license-header
  2. #
  3. # Copyright 2018 Kornia Team
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. from typing import Dict, Optional, Tuple
  18. import torch
  19. from kornia.color import rgb_to_grayscale
  20. from kornia.core import Module, Tensor, concatenate, where, zeros_like
  21. from kornia.feature import LocalFeatureMatcher, LoFTR
  22. from kornia.geometry.homography import find_homography_dlt_iterated
  23. from kornia.geometry.ransac import RANSAC
  24. from kornia.geometry.transform import warp_perspective
  25. class ImageStitcher(Module):
  26. """Stitch two images with overlapping fields of view.
  27. Args:
  28. matcher: image feature matching module.
  29. estimator: method to compute homography, either "vanilla" or "ransac".
  30. "ransac" is slower with a better accuracy.
  31. blending_method: method to blend two images together.
  32. Only "naive" is currently supported.
  33. Note:
  34. Current implementation requires strict image ordering from left to right.
  35. .. code-block:: python
  36. IS = ImageStitcher(KF.LoFTR(pretrained='outdoor'), estimator='ransac').cuda()
  37. # Compute the stitched result with less GPU memory cost.
  38. with torch.inference_mode():
  39. out = IS(img_left, img_right)
  40. # Show the result
  41. plt.imshow(K.tensor_to_image(out))
  42. """
  43. def __init__(self, matcher: Module, estimator: str = "ransac", blending_method: str = "naive") -> None:
  44. super().__init__()
  45. self.matcher = matcher
  46. self.estimator = estimator
  47. self.blending_method = blending_method
  48. if estimator not in ["ransac", "vanilla"]:
  49. raise NotImplementedError(f"Unsupported estimator {estimator}. Use `ransac` or `vanilla` instead.")
  50. if estimator == "ransac":
  51. self.ransac = RANSAC("homography")
  52. def _estimate_homography(self, keypoints1: Tensor, keypoints2: Tensor) -> Tensor:
  53. """Estimate homography by the matched keypoints.
  54. Args:
  55. keypoints1: matched keypoint set from an image, shaped as :math:`(N, 2)`.
  56. keypoints2: matched keypoint set from the other image, shaped as :math:`(N, 2)`.
  57. """
  58. if self.estimator == "vanilla":
  59. homo = find_homography_dlt_iterated(
  60. keypoints2[None], keypoints1[None], torch.ones_like(keypoints1[None, :, 0])
  61. )
  62. elif self.estimator == "ransac":
  63. homo, _ = self.ransac(keypoints2, keypoints1)
  64. homo = homo[None]
  65. else:
  66. raise NotImplementedError(f"Unsupported estimator {self.estimator}. Use `ransac` or `vanilla` instead.")
  67. return homo
  68. def estimate_transform(self, *args: Tensor, **kwargs: Tensor) -> Tensor:
  69. """Compute the corresponding homography."""
  70. kp1, kp2, idx = kwargs["keypoints0"], kwargs["keypoints1"], kwargs["batch_indexes"]
  71. homos = [self._estimate_homography(kp1[idx == i], kp2[idx == i]) for i in range(len(idx.unique()))]
  72. if len(homos) == 0:
  73. raise RuntimeError("Compute homography failed. No matched keypoints found.")
  74. return concatenate(homos)
  75. def blend_image(self, src_img: Tensor, dst_img: Tensor, mask: Tensor) -> Tensor:
  76. """Blend two images together."""
  77. out: Tensor
  78. if self.blending_method == "naive":
  79. out = where(mask == 1, src_img, dst_img)
  80. else:
  81. raise NotImplementedError(f"Unsupported blending method {self.blending_method}. Use `naive`.")
  82. return out
  83. def preprocess(self, image_1: Tensor, image_2: Tensor) -> Dict[str, Tensor]:
  84. """Preprocess input to the required format."""
  85. # TODO: probably perform histogram matching here.
  86. if isinstance(self.matcher, (LoFTR, LocalFeatureMatcher)):
  87. input_dict = { # LofTR works on grayscale images only
  88. "image0": rgb_to_grayscale(image_1),
  89. "image1": rgb_to_grayscale(image_2),
  90. }
  91. else:
  92. raise NotImplementedError(f"The preprocessor for {self.matcher} has not been implemented.")
  93. return input_dict
  94. def postprocess(self, image: Tensor, mask: Tensor) -> Tensor:
  95. # NOTE: assumes no batch mode. This method keeps all valid regions after stitching.
  96. mask_ = mask.sum((0, 1))
  97. index = int(mask_.bool().any(0).long().argmin().item())
  98. if index == 0: # If no redundant space
  99. return image
  100. return image[..., :index]
  101. def on_matcher(self, data: Dict[str, Tensor]) -> Dict[str, Tensor]:
  102. return self.matcher(data)
  103. def stitch_pair(
  104. self,
  105. images_left: Tensor,
  106. images_right: Tensor,
  107. mask_left: Optional[Tensor] = None,
  108. mask_right: Optional[Tensor] = None,
  109. ) -> Tuple[Tensor, Tensor]:
  110. # Compute the transformed images
  111. input_dict = self.preprocess(images_left, images_right)
  112. out_shape = (images_left.shape[-2], images_left.shape[-1] + images_right.shape[-1])
  113. correspondences = self.on_matcher(input_dict)
  114. homo = self.estimate_transform(**correspondences)
  115. src_img = warp_perspective(images_right, homo, out_shape)
  116. dst_img = concatenate([images_left, zeros_like(images_right)], -1)
  117. # Compute the transformed masks
  118. if mask_left is None:
  119. mask_left = torch.ones_like(images_left)
  120. if mask_right is None:
  121. mask_right = torch.ones_like(images_right)
  122. # 'nearest' to ensure no floating points in the mask
  123. src_mask = warp_perspective(mask_right, homo, out_shape, mode="nearest")
  124. dst_mask = concatenate([mask_left, zeros_like(mask_right)], -1)
  125. return self.blend_image(src_img, dst_img, src_mask), (dst_mask + src_mask).bool().to(src_mask.dtype)
  126. def forward(self, *imgs: Tensor) -> Tensor:
  127. img_out = imgs[0]
  128. mask_left = torch.ones_like(img_out)
  129. for i in range(len(imgs) - 1):
  130. img_out, mask_left = self.stitch_pair(img_out, imgs[i + 1], mask_left)
  131. return self.postprocess(img_out, mask_left)