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');
_images/resize_antialias_6_0.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/resize_antialias_7_0.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)
/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/resize_antialias_9_1.png