Rotate image using warp affine transformΒΆ

[1]:
import torch
import kornia

import cv2
[2]:
# read the image with OpenCV
image = cv2.imread('./data/bennett_aden.png')[..., (2,1,0)]
print(image.shape)

img = kornia.image_to_tensor(image)
img = torch.unsqueeze(img.float(), dim=0)  # BxCxHxW
(200, 250, 3)
[3]:
# create transformation (rotation)
alpha = 45.0  # in degrees
angle = torch.ones(1) * alpha

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

# define the scale factor
scale = torch.ones(1)

# compute the transformation matrix
M = kornia.get_rotation_matrix2d(center, angle, scale)

# apply the transformation to original image
_, _, h, w = img.shape
img_warped = kornia.warp_affine(img, M, dsize=(h, w))

# convert back to numpy
image_warped = kornia.tensor_to_image(img_warped.byte()[0])
[4]:
import matplotlib.pyplot as plt
%matplotlib inline

# create the plot
fig, axs = plt.subplots(1, 2, figsize=(16, 10))
axs = axs.ravel()

axs[0].axis('off')
axs[0].set_title('image source')
axs[0].imshow(image)

axs[1].axis('off')
axs[1].set_title('image warped')
axs[1].imshow(image_warped)
[4]:
<matplotlib.image.AxesImage at 0x7efc497dad68>
_images/warp_affine_4_1.png