%%capture
!pip install kornia
!pip install kornia-rs
Rotate image using warp affine transform
Basic
Affine
kornia.geometry
In this tutorial we are going to learn how to rotate an image using the
kornia.gemetry
components.
import io
import requests
def download_image(url: str, filename: str = "") -> str:
= url.split("/")[-1] if len(filename) == 0 else filename
filename # Download
= io.BytesIO(requests.get(url).content)
bytesio # Save file
with open(filename, "wb") as outfile:
outfile.write(bytesio.getbuffer())
return filename
= "https://github.com/kornia/data/raw/main/bennett_aden.png"
url download_image(url)
'bennett_aden.png'
import cv2
import kornia as K
import numpy as np
import torch
import torchvision
from matplotlib import pyplot as plt
load the image using kornia
= K.io.load_image("bennett_aden.png", K.io.ImageLoadType.RGB32)[None, ...] # BxCxHxW x_img
def imshow(input: torch.Tensor, size: tuple = None):
= torchvision.utils.make_grid(input, nrow=4, padding=5)
out = K.utils.tensor_to_image(out)
out_np: np.ndarray =size)
plt.figure(figsize
plt.imshow(out_np)"off")
plt.axis( plt.show()
imshow(x_img)
Define the rotation matrix
# create transformation (rotation)
float = 45.0 # in degrees
alpha: = torch.ones(1) * alpha
angle: torch.tensor
# define the rotation center
= torch.ones(1, 2)
center: torch.tensor 0] = x_img.shape[3] / 2 # x
center[..., 1] = x_img.shape[2] / 2 # y
center[...,
# define the scale factor
= torch.ones(1, 2)
scale: torch.tensor
# compute the transformation matrix
= K.geometry.get_rotation_matrix2d(center, angle, scale) # 1x2x3 M: torch.tensor
Apply the transformation to the original image
= x_img.shape
_, _, h, w = K.geometry.warp_affine(x_img, M, dsize=(h, w))
x_warped: torch.tensor
imshow(x_warped)
Rotate a batch of images
= x_img.repeat(16, 1, 1, 1)
x_batch = K.geometry.rotate(x_batch, torch.linspace(0.0, 360.0, 16))
x_rot
16, 16)) imshow(x_rot, (