Open in Colab

Filtering Operators#

In this tutorial we are going to learn how to apply blurring filters to images with kornia.filters components.

%%capture
!pip install kornia
%%capture
!wget https://github.com/kornia/data/raw/main/drslump.jpg
import cv2
from matplotlib import pyplot as plt
import numpy as np

import torch
import torchvision
import kornia as K
/home/docs/checkouts/readthedocs.org/user_builds/kornia-tutorials/envs/latest/lib/python3.7/site-packages/tqdm/auto.py:22: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm

We use OpenCV to load an image to memory represented in a numpy.ndarray

img_bgr: np.ndarray = cv2.imread('drslump.jpg', cv2.IMREAD_COLOR)

Convert the numpy array to torch

x_bgr: torch.Tensor = K.utils.image_to_tensor(img_bgr)  # CxHxWx
x_bgr = x_bgr[None,...].float() / 255.

x_rgb: torch.Tensor = K.color.bgr_to_rgb(x_bgr)
def imshow(input: torch.Tensor):
    if input.shape != x_rgb.shape:
        input = K.geometry.resize(input, size=(x_rgb.shape[-2:]))
    out = torch.cat([x_rgb, input], dim=-1)
    out = torchvision.utils.make_grid(out, nrow=2, padding=5)
    out_np: np.ndarray = K.utils.tensor_to_image(out)
    plt.imshow(out_np)
    plt.axis('off')
    plt.show()
imshow(x_rgb)
_images/6b8148aeacd991bf1defbb908e18a802dc43f02a0be9b3f4dcf64236f5b37bc5.png

Box Blur#

x_blur: torch.Tensor = K.filters.box_blur(x_rgb, (9, 9))
imshow(x_blur)
_images/35aca84edf457a064b19295126c45e8898bd0c2d3ba220118d32588215024d10.png

Blur Pool#

x_blur: torch.Tensor = K.filters.blur_pool2d(x_rgb, kernel_size=9)
imshow(x_blur)
_images/8f28213754f443be4c0f275baecd1a0e42113dced9bf2ebb43d0756addb6cd56.png

Gaussian Blur#

x_blur: torch.Tensor = K.filters.gaussian_blur2d(x_rgb, (11, 11), (11.0, 11.0))
imshow(x_blur)
_images/4ac7bed5c5e19624c86f2daaed8806781e42d067d0250738f161fb84c6e4e49f.png

Max Pool#

x_blur: torch.Tensor = K.filters.max_blur_pool2d(x_rgb, kernel_size=11)
imshow(x_blur)
_images/f3e16a0078ddc07432bd84daf89210eb0765be55d3f28760b7c65a5719078ca9.png

Median Blur#

x_blur: torch.Tensor = K.filters.median_blur(x_rgb, (5, 5))
imshow(x_blur)
_images/017e1234018bc82a9cf1411484c94868c62ffdc25dc6b83f850c1deab01d16de.png

Motion Blur#

x_blur: torch.Tensor = K.filters.motion_blur(x_rgb, 9, 90., 1)
imshow(x_blur)
_images/890e6b46603dfaa89c971a66ceeebb0eccf794257484bb7f9b8b545723448c44.png