How to do Affine Transform in OpenCV Python

You can do affine transform using OpenCV Python by following the given steps. I highly recommend you get the “Computer Vision: Models, Learning, and Inference Book” to learn Computer Vision.

How to do Affine Transform in OpenCV Python
How to do Affine Transform in OpenCV Python

Step 1

Import the required libraries. If OpenCV is not installed in your system then first install it using This Method.

import cv2
#cv2 is used for OpenCV library
import numpy as np

Step 2

Now Read the Image. The image should be in the current working directory. Otherwise, mention the location of the image.

img =cv2.imread('cat.jpg')

Step 3

Now make two variables rows and cols. Use these two variables to make the final points of the required image.

rows, cols = img.shape[:2]
initial_points = np.float32([[0,0],[cols-1,0],[0,rows-1]])
final_points = np.float32([[0,0],[cols-1,0],[int(-0.30*cols),int(0.90*rows)]])

Step 4

First, make an affine_matrix using the function cv2.getAffineTransform. Then apply the matrix to the image using the function cv2.warpAffine.

affine_matrix = cv2.getAffineTransform(initial_points,final_points)
affine = cv2.warpAffine(img,affine_matrix,(cols,rows))

Step 5

Now display both images.

cv2.imshow('Cat',img)
cv2.imshow('Affine Transformation',affine)
cv2.waitKey(0)
cv2.destroyAllWindows()
Cat
Affine Transformation

Leave a Comment

Your email address will not be published.