Open in Colab

Image Enhancement

In this tutorial we are going to learn how to tweak image properties using the compoments from kornia.enhance.

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

import torch
import torchvision
import kornia as K
def imshow(input: torch.Tensor):
    out: torch.Tensor = torchvision.utils.make_grid(input, nrow=2, padding=5)
    out_np: np.ndarray = K.utils.tensor_to_image(out)
    plt.imshow(out_np)
    plt.axis('off')
    plt.show()

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

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

Convert the numpy array to torch

x_bgr: torch.Tensor = K.utils.image_to_tensor(img_bgr)
x_rgb: torch.Tensor = K.color.bgr_to_rgb(x_bgr)

Create batch and normalize

x_rgb = x_rgb.expand(4, -1, -1, -1)  # 4xCxHxW
x_rgb = x_rgb.float() / 255.0
imshow(x_rgb)
_images/image_enhancement_11_0.png

Adjust brightness

x_out: torch.Tensor = K.enhance.adjust_brightness(
    x_rgb, torch.linspace(0.2, 0.8, 4))
imshow(x_out)
_images/image_enhancement_13_0.png

Adjust Contrast

x_out: torch.Tensor = K.enhance.adjust_contrast(
    x_rgb, torch.linspace(0.5, 1., 4))
imshow(x_out)
_images/image_enhancement_15_0.png

Adjust Saturation

x_out: torch.Tensor = K.enhance.adjust_saturation(
    x_rgb, torch.linspace(0., 1., 4))
imshow(x_out)
_images/image_enhancement_17_0.png

Adjust Gamma

x_out: torch.Tensor = K.enhance.adjust_gamma(
    x_rgb, torch.tensor([0.2, 0.4, 0.5, 0.6]))
imshow(x_out)
_images/image_enhancement_19_0.png

Adjust Hue

x_out: torch.Tensor = K.enhance.adjust_hue(
    x_rgb, torch.linspace(0., 3.14159, 4))
imshow(x_out)
_images/image_enhancement_21_0.png