Open in Colab

Blur image using GaussianBlur operator#

In this tutorial we show how easily one can apply typical image transformations using Kornia.

Enjoy the example!

Preparation#

We first install Kornia.

%%capture
%matplotlib inline
!pip install kornia
import kornia
kornia.__version__
/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
'0.6.6-dev'

Now we download the example image.

%%capture
!wget https://github.com/kornia/data/raw/main/bennett_aden.png

Example#

We first import the required libraries and load the data.

import torch
import kornia
import cv2
import numpy as np

import matplotlib.pyplot as plt

# read the image with OpenCV
img: np.ndarray = cv2.imread('./bennett_aden.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# convert to torch tensor
data: torch.tensor = kornia.image_to_tensor(img, keepdim=False)  # BxCxHxW

To apply a filter, we create the Gaussian Blur filter object and apply it to the data:

# create the operator
gauss = kornia.filters.GaussianBlur2d((11, 11), (10.5, 10.5))

# blur the image
x_blur: torch.tensor = gauss(data.float())

That’s it! We can compare the pre-transform image and the post-transform image:

# convert back to numpy
img_blur: np.ndarray = kornia.tensor_to_image(x_blur.byte())

# Create the plot
fig, axs = plt.subplots(1, 2, figsize=(16, 10))
axs = axs.ravel()

axs[0].axis('off')
axs[0].set_title('image source')
axs[0].imshow(img)

axs[1].axis('off')
axs[1].set_title('image blurred')
axs[1].imshow(img_blur)

pass
_images/51f61d36565db45aa554ac4177e4fe122d564b88748ab5bb2f8c84e72ab7f96d.png