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

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/filtering_operators_9_0.png

Box Blur

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

Blur Pool

x_blur: torch.Tensor = K.filters.blur_pool2d(x_rgb, kernel_size=9)
imshow(x_blur)
/home/docs/checkouts/readthedocs.org/user_builds/kornia-tutorials/envs/latest/lib/python3.7/site-packages/torch/nn/functional.py:3635: UserWarning: Default upsampling behavior when mode=bilinear is changed to align_corners=False since 0.4.0. Please specify align_corners=True if the old behavior is desired. See the documentation of nn.Upsample for details.
  "See the documentation of nn.Upsample for details.".format(mode)
_images/filtering_operators_13_1.png

Gaussian Blur

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

Max Pool

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

Median Blur

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

Motion Blur

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