# 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.
Author

Edgar Riba

Published

July 6, 2021

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

import requests

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

return filename

``'bennett_aden.png'``
``````import cv2
import kornia as K
import numpy as np
import torch
import torchvision
from matplotlib import pyplot as plt``````

``x_img = K.io.load_image("bennett_aden.png", K.io.ImageLoadType.RGB32)[None, ...]  # BxCxHxW``
``````def imshow(input: torch.Tensor, size: tuple = None):
out_np: np.ndarray = K.utils.tensor_to_image(out)
plt.figure(figsize=size)
plt.imshow(out_np)
plt.axis("off")
plt.show()``````
``imshow(x_img)``

## Define the rotation matrix

``````# create transformation (rotation)
alpha: float = 45.0  # in degrees
angle: torch.tensor = torch.ones(1) * alpha

# define the rotation center
center: torch.tensor = torch.ones(1, 2)
center[..., 0] = x_img.shape[3] / 2  # x
center[..., 1] = x_img.shape[2] / 2  # y

# define the scale factor
scale: torch.tensor = torch.ones(1, 2)

# compute the transformation matrix
M: torch.tensor = K.geometry.get_rotation_matrix2d(center, angle, scale)  # 1x2x3``````

## Apply the transformation to the original image

``````_, _, h, w = x_img.shape
x_warped: torch.tensor = K.geometry.warp_affine(x_img, M, dsize=(h, w))

imshow(x_warped)``````

## Rotate a batch of images

``````x_batch = x_img.repeat(16, 1, 1, 1)
x_rot = K.geometry.rotate(x_batch, torch.linspace(0.0, 360.0, 16))

imshow(x_rot, (16, 16))``````