Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

add laplacian pyramid (#1816)

Lafith Mattara55dbab555b00
diff --git a/docs/generate_example_images.py b/docs/generate_example_images.py
index f9f46b746..3bc8a62ae 100644
--- a/docs/generate_example_images.py
+++ b/docs/generate_example_images.py
@@ -322,6 +322,7 @@ def main():
"pyrdown": ((), 1),
"pyrup": ((), 1),
"build_pyramid": ((3,), 1),
+ "build_laplacian_pyramid": ((3,), 1),
}
# ITERATE OVER THE TRANSFORMS
for fn_name, (args, num_samples) in transforms.items():
@@ -340,8 +341,22 @@ def main():
out_tmp = torch.nn.functional.pad(pyr, (0, (w - w_new), 0, (h - h_new)))
_out.append(out_tmp)
out = torch.cat(_out)
+
+ if fn_name == "build_laplacian_pyramid":
+ h_, w_ = out[0].shape[-2:]
+ _out = [out[0]]
+ for pyr in out[1:]:
+ h_new, w_new = pyr.shape[-2:]
+ out_tmp = torch.nn.functional.pad(pyr, (0, (w_ - w_new), 0, (h_ - h_new)))
+ print(out_tmp.size())
+ _out.append(out_tmp)
+ out = torch.cat(_out)
+
# save the output image
- out = torch.cat([img_in[0], *(out[i] for i in range(out.size(0)))], dim=-1)
+ if fn_name != "build_laplacian_pyramid":
+ out = torch.cat([img_in[0], *(out[i] for i in range(out.size(0)))], dim=-1)
+ else:
+ out = torch.cat([*(out[i] for i in range(out.size(0)))], dim=-1)
out_np = K.utils.tensor_to_image((out * 255.0).byte())
cv2.imwrite(str(OUTPUT_PATH / f"{fn_name}.png"), out_np)
sig = f"{fn_name}({', '.join([str(a) for a in args])})"
diff --git a/docs/source/geometry.transform.rst b/docs/source/geometry.transform.rst
index c459fa619..ac45b71fe 100644
--- a/docs/source/geometry.transform.rst
+++ b/docs/source/geometry.transform.rst
@@ -34,6 +34,7 @@ Image 2d transforms
.. autofunction:: pyrdown
.. autofunction:: pyrup
.. autofunction:: build_pyramid
+.. autofunction:: build_laplacian_pyramid
Matrix transformations
----------------------
diff --git a/docs/source/references.bib b/docs/source/references.bib
index 4e340a95f..674253071 100644
--- a/docs/source/references.bib
+++ b/docs/source/references.bib
@@ -249,3 +249,12 @@ month = {mar}
pages = {81 - 93},
volume = {141}
}
+
+@incollection{burt1987laplacian,
+ title={The Laplacian pyramid as a compact image code},
+ author={Burt, Peter J and Adelson, Edward H},
+ booktitle={Readings in computer vision},
+ pages={671--679},
+ year={1987},
+ publisher={Elsevier}
+}
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index 7adcc611b..767837a6d 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -5,12 +5,14 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
+from kornia.core import Tensor
from kornia.filters import filter2d, gaussian_blur2d
+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE
-__all__ = ["PyrDown", "PyrUp", "ScalePyramid", "pyrdown", "pyrup", "build_pyramid"]
+__all__ = ["PyrDown", "PyrUp", "ScalePyramid", "pyrdown", "pyrup", "build_pyramid", "build_laplacian_pyramid"]
-def _get_pyramid_gaussian_kernel() -> torch.Tensor:
+def _get_pyramid_gaussian_kernel() -> Tensor:
"""Utility function that return a pre-computed gaussian kernel."""
return (
torch.tensor(
@@ -56,7 +58,7 @@ class PyrDown(nn.Module):
self.align_corners: bool = align_corners
self.factor: float = factor
- def forward(self, input: torch.Tensor) -> torch.Tensor:
+ def forward(self, input: Tensor) -> Tensor:
return pyrdown(input, self.border_type, self.align_corners, self.factor)
@@ -86,7 +88,7 @@ class PyrUp(nn.Module):
self.border_type: str = border_type
self.align_corners: bool = align_corners
- def forward(self, input: torch.Tensor) -> torch.Tensor:
+ def forward(self, input: Tensor) -> Tensor:
return pyrup(input, self.border_type, self.align_corners)
@@ -184,7 +186,7 @@ class ScalePyramid(nn.Module):
cur_level = x
return cur_level, cur_sigma, pixel_distance
- def forward(self, x: torch.Tensor) -> Tuple[List, List, List]: # type: ignore
+ def forward(self, x: Tensor) -> Tuple[List, List, List]: # type: ignore
bs, _, _, _ = x.size()
cur_level, cur_sigma, pixel_distance = self.get_first_level(x)
@@ -227,9 +229,7 @@ class ScalePyramid(nn.Module):
return pyr, sigmas, pixel_dists
-def pyrdown(
- input: torch.Tensor, border_type: str = 'reflect', align_corners: bool = False, factor: float = 2.0
-) -> torch.Tensor:
+def pyrdown(input: Tensor, border_type: str = 'reflect', align_corners: bool = False, factor: float = 2.0) -> Tensor:
r"""Blur a tensor and downsamples it.
.. image:: _static/img/pyrdown.png
@@ -251,16 +251,16 @@ def pyrdown(
tensor([[[[ 3.7500, 5.2500],
[ 9.7500, 11.2500]]]])
"""
- if not len(input.shape) == 4:
- raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
- kernel: torch.Tensor = _get_pyramid_gaussian_kernel()
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
+
+ kernel: Tensor = _get_pyramid_gaussian_kernel()
_, _, height, width = input.shape
# blur image
- x_blur: torch.Tensor = filter2d(input, kernel, border_type)
+ x_blur: Tensor = filter2d(input, kernel, border_type)
# TODO: use kornia.geometry.resize/rescale
# downsample.
- out: torch.Tensor = F.interpolate(
+ out: Tensor = F.interpolate(
x_blur,
size=(int(float(height) / factor), int(float(width) // factor)),
mode='bilinear',
@@ -269,7 +269,7 @@ def pyrdown(
return out
-def pyrup(input: torch.Tensor, border_type: str = 'reflect', align_corners: bool = False) -> torch.Tensor:
+def pyrup(input: Tensor, border_type: str = 'reflect', align_corners: bool = False) -> Tensor:
r"""Upsample a tensor and then blurs it.
.. image:: _static/img/pyrup.png
@@ -291,25 +291,23 @@ def pyrup(input: torch.Tensor, border_type: str = 'reflect', align_corners: bool
[1.5000, 1.6250, 1.8750, 2.0000],
[1.7500, 1.8750, 2.1250, 2.2500]]]])
"""
- if not len(input.shape) == 4:
- raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
- kernel: torch.Tensor = _get_pyramid_gaussian_kernel()
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
+
+ kernel: Tensor = _get_pyramid_gaussian_kernel()
# upsample tensor
_, _, height, width = input.shape
# TODO: use kornia.geometry.resize/rescale
- x_up: torch.Tensor = F.interpolate(
- input, size=(height * 2, width * 2), mode='bilinear', align_corners=align_corners
- )
+ x_up: Tensor = F.interpolate(input, size=(height * 2, width * 2), mode='bilinear', align_corners=align_corners)
# blurs upsampled tensor
- x_blur: torch.Tensor = filter2d(x_up, kernel, border_type)
+ x_blur: Tensor = filter2d(x_up, kernel, border_type)
return x_blur
def build_pyramid(
- input: torch.Tensor, max_level: int, border_type: str = 'reflect', align_corners: bool = False
-) -> List[torch.Tensor]:
- r"""Construct the Gaussian pyramid for an image.
+ input: Tensor, max_level: int, border_type: str = 'reflect', align_corners: bool = False
+) -> List[Tensor]:
+ r"""Construct the Gaussian pyramid for a tensor image.
.. image:: _static/img/build_pyramid.png
@@ -329,24 +327,85 @@ def build_pyramid(
- Input: :math:`(B, C, H, W)`
- Output :math:`[(B, C, H, W), (B, C, H/2, W/2), ...]`
"""
- if not isinstance(input, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
-
- if not len(input.shape) == 4:
- raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
-
- if not isinstance(max_level, int) or max_level < 0:
- raise ValueError(f"Invalid max_level, it must be a positive integer. Got: {max_level}")
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
+ KORNIA_CHECK(
+ isinstance(max_level, int) or max_level < 0,
+ f"Invalid max_level, it must be a positive integer. Got: {max_level}",
+ )
# create empty list and append the original image
- pyramid: List[torch.Tensor] = []
+ pyramid: List[Tensor] = []
pyramid.append(input)
# iterate and downsample
-
for _ in range(max_level - 1):
- img_curr: torch.Tensor = pyramid[-1]
- img_down: torch.Tensor = pyrdown(img_curr, border_type, align_corners)
+ img_curr: Tensor = pyramid[-1]
+ img_down: Tensor = pyrdown(img_curr, border_type, align_corners)
pyramid.append(img_down)
return pyramid
+
+
+def is_powerof_two(x):
+ # check if number x is a power of two
+ return x and (not (x & (x - 1)))
+
+
+def find_next_powerof_two(x):
+ # return the nearest power of 2
+ n = math.ceil(math.log(x) / math.log(2))
+ return 2**n
+
+
+def build_laplacian_pyramid(
+ input: Tensor, max_level: int, border_type: str = 'reflect', align_corners: bool = False
+) -> List[Tensor]:
+ r"""Construct the Laplacian pyramid for a tensor image.
+
+ The function constructs a vector of images and builds the Laplacian pyramid
+ by recursively computing the difference after applying
+ pyrUp to the adjacent layer in it's Gaussian pyramid.
+
+ See :cite:`burt1987laplacian` for more details.
+
+ Args:
+ input : the tensor to be used to construct the pyramid with shape :math:`(B, C, H, W)`.
+ max_level: 0-based index of the last (the smallest) pyramid layer.
+ It must be non-negative.
+ border_type: the padding mode to be applied before convolving.
+ The expected modes are: ``'constant'``, ``'reflect'``,
+ ``'replicate'`` or ``'circular'``.
+ align_corners: interpolation flag.
+
+ Return:
+ Output: :math:`[(B, C, H, W), (B, C, H/2, W/2), ...]`
+ """
+
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
+ KORNIA_CHECK(
+ isinstance(max_level, int) or max_level < 0,
+ f"Invalid max_level, it must be a positive integer. Got: {max_level}",
+ )
+
+ h = input.size()[2]
+ w = input.size()[3]
+ require_padding = not (is_powerof_two(w) or is_powerof_two(h))
+
+ if require_padding:
+ # in case of arbitrary shape tensor image need to be padded.
+ # Reference: https://stackoverflow.com/a/29967555
+ pad = (0, find_next_powerof_two(w) - w, 0, find_next_powerof_two(h) - h)
+ input = F.pad(input, pad, "reflect")
+
+ # create gaussian pyramid
+ gaussian_pyramid: List[Tensor] = build_pyramid(input, max_level, border_type, align_corners)
+ # create empty list
+ laplacian_pyramid: List[Tensor] = []
+
+ # iterate and compute difference of adjacent layers in a gaussian pyramid
+ for i in range(max_level - 1):
+ img_expand: Tensor = pyrup(gaussian_pyramid[i + 1], border_type, align_corners)
+ laplacian: Tensor = gaussian_pyramid[i] - img_expand
+ laplacian_pyramid.append(laplacian)
+ laplacian_pyramid.append(gaussian_pyramid[-1])
+ return laplacian_pyramid
diff --git a/test/geometry/transform/test_pyramid.py b/test/geometry/transform/test_pyramid.py
index d2bd973d5..c93461e81 100644
--- a/test/geometry/transform/test_pyramid.py
+++ b/test/geometry/transform/test_pyramid.py
@@ -155,3 +155,32 @@ class TestBuildPyramid:
img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
img = utils.tensor_to_gradcheck_var(img) # to var
assert gradcheck(kornia.geometry.transform.build_pyramid, (img, max_level), raise_exception=True)
+
+
+class TestBuildLaplacianPyramid:
+ def test_smoke(self, device, dtype):
+ input = torch.ones(1, 2, 4, 5, device=device, dtype=dtype)
+ pyramid = kornia.geometry.transform.build_laplacian_pyramid(input, max_level=1)
+ assert len(pyramid) == 1
+ assert pyramid[0].shape == (1, 2, 4, 5)
+
+ @pytest.mark.parametrize("batch_size", (1, 2, 3))
+ @pytest.mark.parametrize("channels", (1, 3))
+ @pytest.mark.parametrize("max_level", (2, 3, 4))
+ def test_num_levels(self, batch_size, channels, max_level, device, dtype):
+ height, width = 16, 32
+ input = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
+ pyramid = kornia.geometry.transform.build_laplacian_pyramid(input, max_level)
+ assert len(pyramid) == max_level
+ for i in range(1, max_level):
+ img = pyramid[i]
+ denom = 2**i
+ expected_shape = (batch_size, channels, height // denom, width // denom)
+ assert img.shape == expected_shape
+
+ def test_gradcheck(self, device, dtype):
+ max_level = 1
+ batch_size, channels, height, width = 1, 2, 7, 9
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ assert gradcheck(kornia.geometry.transform.build_laplacian_pyramid, (img, max_level), raise_exception=True)