Image Enhancement

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

Edgar Riba

Published

July 5, 2021

Open in google colab

%%capture
!pip install kornia
!pip install kornia-rs
import io

import requests


def download_image(url: str, filename: str = "") -> str:
    filename = url.split("/")[-1] if len(filename) == 0 else filename
    # Download
    bytesio = io.BytesIO(requests.get(url).content)
    # Save file
    with open(filename, "wb") as outfile:
        outfile.write(bytesio.getbuffer())

    return filename


download_image("https://github.com/kornia/data/raw/main/ninja_turtles.jpg")
'ninja_turtles.jpg'
import kornia as K
import numpy as np
import torch
import torchvision
from matplotlib import pyplot as plt
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 Kornia to load an image to memory represented as a tensor

x_rgb = K.io.load_image("ninja_turtles.jpg", K.io.ImageLoadType.RGB32)[None, ...]

Create batch

x_rgb = x_rgb.expand(4, -1, -1, -1)  # 4xCxHxW
imshow(x_rgb)

Adjust brightness

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

Adjust Contrast

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

Adjust Saturation

x_out: torch.Tensor = K.enhance.adjust_saturation(x_rgb, torch.linspace(0.0, 1.0, 4))
imshow(x_out)

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)

Adjust Hue

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