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
/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
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/2d556bddda966a9ec1888c7a6b30749aebeedf78bcd087fa713a03991c3e34aa.png

Adjust brightness#

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

Adjust Contrast#

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

Adjust Saturation#

x_out: torch.Tensor = K.enhance.adjust_saturation(
    x_rgb, torch.linspace(0., 1., 4))
imshow(x_out)
_images/249cf91e8bb6a562c6135d4726cf8a16f1b674408c58fa73c24c92927c5fd247.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/079cf1e16a5eb53350dffbdcd6b96a59436a973e44574e26b9d3c2971822f7ba.png

Adjust Hue#

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