Open in Colab

Image Enhancement#

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

!pip install kornia
import cv2
from matplotlib import pyplot as plt
import numpy as np

import torch
import torchvision
import kornia as K
/home/docs/checkouts/ TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See
  from .autonotebook import tqdm as notebook_tqdm
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)

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

Adjust brightness#

x_out: torch.Tensor = K.enhance.adjust_brightness(
    x_rgb, torch.linspace(0.2, 0.8, 4))

Adjust Contrast#

x_out: torch.Tensor = K.enhance.adjust_contrast(
    x_rgb, torch.linspace(0.5, 1., 4))

Adjust Saturation#

x_out: torch.Tensor = K.enhance.adjust_saturation(
    x_rgb, torch.linspace(0., 1., 4))

Adjust Gamma#

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

Adjust Hue#

x_out: torch.Tensor = K.enhance.adjust_hue(
    x_rgb, torch.linspace(0., 3.14159, 4))