Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

add image resgistration to doc tasks (#1262)

Edgar Riba2dd8ea00e9ee
diff --git a/docs/requirements.txt b/docs/requirements.txt
index 2758f7445..b8b889495 100644
--- a/docs/requirements.txt
+++ b/docs/requirements.txt
@@ -7,6 +7,7 @@ matplotlib
sphinx>=4.0
sphinx_rtd_theme>0.5
sphinxcontrib-bibtex
+sphinxcontrib-youtube
sphinx-autodoc-typehints>=1.0
sphinx-copybutton>=0.3
sphinx-autodoc-defaultargs
diff --git a/docs/source/_static/image_registration.py b/docs/source/_static/image_registration.py
new file mode 100644
index 000000000..478ec4199
--- /dev/null
+++ b/docs/source/_static/image_registration.py
@@ -0,0 +1,38 @@
+import os
+
+import cv2
+import imageio
+import matplotlib.pyplot as plt
+import torch
+
+import kornia as K
+import kornia.geometry as KG
+
+
+def load_timg(file_name):
+ """Loads the image with OpenCV and converts to torch.Tensor."""
+ assert os.path.isfile(file_name), f"Invalid file {file_name}" # nosec
+ # load image with OpenCV
+ img = cv2.imread(file_name, cv2.IMREAD_COLOR)
+ # convert image to torch tensor
+ tensor = K.image_to_tensor(img, None).float() / 255.
+ return K.color.bgr_to_rgb(tensor)
+
+registrator = KG.ImageRegistrator('similarity')
+
+img1 = K.resize(load_timg('/Users/oldufo/datasets/stewart/MR-CT/CT.png'), (400, 600))
+img2 = K.resize(load_timg('/Users/oldufo/datasets/stewart/MR-CT/MR.png'), (400, 600))
+model, intermediate = registrator.register(img1, img2, output_intermediate_models=True)
+
+video_writer = imageio.get_writer('medical_registration.gif', fps=2)
+
+timg_dst_first = img1.clone()
+timg_dst_first[0, 0, :, :] = img2[0, 0, :, :]
+video_writer.append_data(K.tensor_to_image((timg_dst_first * 255.).byte()))
+
+with torch.no_grad():
+ for m in intermediate:
+ timg_dst = KG.homography_warp(img1, m, img2.shape[-2:])
+ timg_dst[0, 0, :, :] = img2[0, 0, :, :]
+ video_writer.append_data(K.tensor_to_image((timg_dst_first * 255.).byte()))
+video_writer.close()
diff --git a/docs/source/conf.py b/docs/source/conf.py
index 3ca083c22..a0d3f7853 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -46,6 +46,7 @@ extensions = [
'sphinx.ext.viewcode',
'sphinx.ext.githubpages',
'sphinxcontrib.bibtex',
+ 'sphinxcontrib.youtube',
]
# substitutes the default values
diff --git a/docs/source/index.rst b/docs/source/index.rst
index a1acd9417..774102328 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -5,7 +5,7 @@ Kornia Documentation
.. toctree::
:maxdepth: 2
- :caption: Get Started
+ :caption: GET STARTED
introduction
installation
@@ -13,7 +13,13 @@ Kornia Documentation
.. toctree::
:maxdepth: 2
- :caption: Package Reference
+ :caption: KORNIA UNIVERSE
+
+ tasks
+
+.. toctree::
+ :maxdepth: 2
+ :caption: API REFERENCE
augmentation
color
@@ -28,7 +34,7 @@ Kornia Documentation
.. toctree::
:maxdepth: 2
- :caption: Community
+ :caption: COMMUNITY
contribute
faqs
diff --git a/docs/source/tasks.rst b/docs/source/tasks.rst
new file mode 100644
index 000000000..0e98d15d8
--- /dev/null
+++ b/docs/source/tasks.rst
@@ -0,0 +1,42 @@
+Supported Applications
+======================
+
+Kornia provides from bottom to top granularity in order to implement Computer Vision related applications.
+
+In this section, we showcase our high-level API in terms of abstraction for common Computer Vision algorithms
+that can be used across different domains such as Robotics, Industrial applications or for the AR/VR industry.
+
+Image Registration
+------------------
+
+Image registration is the process of transforming different sets of data into one coordinate system. Data may be multiple photographs, data from different sensors, times, depths, or viewpoints. It is used in computer vision, medical imaging, and compiling and analyzing images and data from satellites. Registration is necessary in order to be able to compare or integrate the data obtained from these different measurements.
+
+Learn more @ PWC : `https://paperswithcode.com/task/image-registration <https://paperswithcode.com/task/image-registration>`_
+
+.. youtube:: I-g3EhBIsDs
+
+We provide the :py:class:`~kornia.geometry.transform.image_registrator.ImageRegistrator` API from which you can leverage to align automatically two images by a process of direct optimisation using the PyTorch Autograd differentiability.
+
+.. code:: python
+
+ from kornia.geometry import ImageRegistrator
+ img_src = torch.rand(1, 1, 32, 32)
+ img_dst = torch.rand(1, 1, 32, 32)
+ registrator = ImageRegistrator('similarity')
+ homo = registrator.register(img_src, img_dst)
+
+Then, if you want to perform a more sophisticated process:
+
+.. literalinclude:: _static/image_registration.py
+
+To reproduce the same results as in the showed video you can go through or full tutorial using Colab found `here <https://kornia-tutorials.readthedocs.io/en/latest/image_registration.html>`_ .
+
+Video Deblurring
+----------------
+
+**COMING SOON**
+
+Image Matching
+--------------
+
+**COMING SOON**
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.py
index 07b8f41c7..4f722d725 100644
--- a/kornia/geometry/transform/image_registrator.py
+++ b/kornia/geometry/transform/image_registrator.py
@@ -1,4 +1,4 @@
-from typing import List, Optional, Tuple, Type, Union
+from typing import Callable, List, Optional, Tuple, Type, Union
import torch
import torch.nn as nn
@@ -39,14 +39,16 @@ class Homography(nn.Module):
r"""Single-batch homography".
Returns:
- Homography with shape :math:`(1, 3, 3)`"""
+ Homography matrix with shape :math:`(1, 3, 3)`.
+ """
return torch.unsqueeze(self.model / self.model[2, 2], dim=0) # 1x3x3
def forward_inverse(self) -> torch.Tensor:
r"""Interted Single-batch homography".
Returns:
- Homography with shape :math:`(1, 3, 3)`"""
+ Homography martix with shape :math:`(1, 3, 3)`.
+ """
return torch.unsqueeze(torch.inverse(self.model), dim=0)
@@ -83,7 +85,7 @@ class Similarity(nn.Module):
return f'{self.__class__.__name__}(angle = {self.rot},\
\n shift={self.shift}, \n scale={self.scale})'
- def reset_model(self):
+ def reset_model(self) -> None:
"""Initializes the model with identity transform."""
torch.nn.init.zeros_(self.rot)
torch.nn.init.zeros_(self.shift)
@@ -108,7 +110,7 @@ class Similarity(nn.Module):
class ImageRegistrator(nn.Module):
- r"""Module, which performs optimization-based image registration
+ r"""Module, which performs optimization-based image registration.
Args:
model_type: Geometrical model for registration. Can be string or Module.
@@ -118,17 +120,26 @@ class ImageRegistrator(nn.Module):
lr: learning rate for optimization.
num_iterations: maximum number of iterations.
tolerance: stop optimizing if loss difference is less. default 1e-4.
- warper: if model_type is not string, one needs to provide warper object."""
+ warper: if model_type is not string, one needs to provide warper object.
+
+ Example:
+ >>> from kornia.geometry import ImageRegistrator
+ >>> img_src = torch.rand(1, 1, 32, 32)
+ >>> img_dst = torch.rand(1, 1, 32, 32)
+ >>> registrator = ImageRegistrator('similarity')
+ >>> homo = registrator.register(img_src, img_dst)
+ """
known_models = ['homography',
'similarity',
'translation',
'scale',
'rotation']
+ # TODO: resolve better type, potentially using factory.
def __init__(self,
model_type='homography',
optimizer=optim.Adam,
- loss_fn=F.l1_loss,
+ loss_fn: Callable = F.l1_loss,
pyramid_levels: int = 5,
lr: float = 1e-3,
num_iterations: int = 100,
@@ -206,17 +217,12 @@ class ImageRegistrator(nn.Module):
Returns:
the transformation between two images, shape depends on the model,
- typically [1x3x3] tensor for string model_types
-
- Example:
- >>> from kornia.geometry import ImageRegistrator
- >>> img_src = torch.rand(1, 1, 32, 32)
- >>> img_dst = torch.rand(1, 1, 32, 32)
- >>> registrator = ImageRegistrator('similarity')
- >>> homo = registrator.register(img_src, img_dst)"""
+ typically [1x3x3] tensor for string model_types.
+
+ """
self.reset_model()
# ToDo: better parameter passing to optimizer
- opt = self.optimizer(self.model.parameters(), lr=self.lr)
+ opt: optim.Optimizer = self.optimizer(self.model.parameters(), lr=self.lr)
# compute the gaussian pyramids
# [::-1] because we have to register from coarse to fine
@@ -251,14 +257,14 @@ class ImageRegistrator(nn.Module):
return self.model()
def warp_src_into_dst(self, src_img: torch.Tensor) -> torch.Tensor:
- r'''Warps src_img with estimated model'''
+ r"""Warps src_img with estimated model."""
_height, _width = src_img.shape[-2:]
warper = self.warper(_height, _width)
img_src_to_dst = warper(src_img, self.model())
return img_src_to_dst
def warp_dst_inro_src(self, dst_img: torch.Tensor) -> torch.Tensor:
- r'''Warps src_img with inverted estimated model'''
+ r"""Warps src_img with inverted estimated model."""
_height, _width = dst_img.shape[-2:]
warper = self.warper(_height, _width)
img_dst_to_src = warper(dst_img, self.model.forward_inverse())