Open in Colab

Resize anti-alias#

In this tutorial we are going to learn how to resize an image with anti-alias.

Install Kornia#

%%capture
!pip install kornia

Prepare the data#

Download an example image

%%capture
!wget https://github.com/kornia/data/raw/main/drslump.jpg

Load the image using OpenCV and plot it

from matplotlib import pyplot as plt
import cv2
import numpy as np
import kornia as K

# load using opencv and convert to RGB
img_bgr: np.array = cv2.imread('drslump.jpg', cv2.IMREAD_COLOR)
img_rgb: np.array = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
plt.imshow(img_rgb); plt.axis('off');
/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
_images/1a1881365a11d7eee9abd67f8632827e0a56fd457cd67af2a397f1e4ebfa6636.png
import torch
import torchvision

def imshow(input: torch.Tensor):
    out: torch.Tensor = torchvision.utils.make_grid(input, nrow=2)
    out_np: np.array = K.utils.tensor_to_image(out)
    plt.figure(figsize=(20,10))
    plt.imshow(out_np); plt.axis('off');

# stack four identical images
data: torch.Tensor = K.utils.image_to_tensor(img_rgb).float()/255.  # 1xCxHxW
# plot
imshow(data)
_images/b8490bb7db1664c9fed46eb69925668224b6305d6392216f7bc4b2a6ea1a98f6.png

Plain resize vs Antializased resize#

x_025: torch.Tensor = K.geometry.rescale(data, (0.125, 0.125))
x_025AA: torch.Tensor = K.geometry.rescale(data, (0.125, 0.125), antialias=True)
out = torch.stack([x_025, x_025AA], dim=0)
imshow(out)
_images/2455a092f52921e70508d1669fc4382e4ac0f17715ef8a371ef0bf126cd7c923.png