OpenCv Perspective Transformation

Raqueeb Shaikh
Analytics Vidhya
Published in
3 min readJun 26, 2020

Perspective Transform is a feature that is very useful if you want to align the image properly . It transform the image in a straight manner after Perspective Transformation is applied to it.
A classic Example of this if to transform the page on table to only select the page and transform it so that it appears as a top view of the image

Before we go into OpenCv Perspective Transform function we will look slightly into how the formula,algorithm looks and what goes behind the scene .

The above image on the left has —
Coordinates [[50,0],[150,0],[0,200],[200,200]]
Which have to be transformed to the new Coordinate —
New Coordinates [[0,0],[200,0],[0,200],[200,200]]

Calculation Example Given Below —

Below is second calculation example

As you can see from the image all the horizontal Parallel lines are kept Parallel after transformation . Vertical Parallel lines are not Parallel to each other after Transformation .

Implementation of Perspective Transformation in OpenCv

import cv2
from operator import itemgetter
from glob import glob
import matplotlib.pyplot as plt
paper = cv2.imread('./Photos/book.jpg')
# Coordinates that you want to Perspective Transform
pts1 = np.float32([[219,209],[612,8],[380,493],[785,271]])
# Size of the Transformed Image
pts2 = np.float32([[0,0],[500,0],[0,400],[500,400]])
for val in pt1:
cv2.circle(paper,(val[0],val[1]),5,(0,255,0),-1)
M = cv2.getPerspectiveTransform(pt1,pts2)
dst = cv2.warpPerspective(paper,M,(500,400))
plt.imshow(dst)

As you can see from the above image how the Perspective Transform function maintains the Horizontal lines in the image and manages to get the top view for the paper . Some more example images given below

--

--