I wanted to learn OpenCV Perspective Transform. Tutorials that I found on the internet bit complex for me to really understand what it is all about. I have to read few tutorials before really understand it.
In layman term, perspective transform is taking a rectangle area from original image and re-project the cut rectangle to our defined size canvas.
To do this, you just need 4 corner pixel points and perspective transform will do all other pixels calculation automatically based on those 4 pixels points.
The Required Pixel Points
The corner pixels points must follow the order as shown in below image.

This is considered the source pixel points.
The destination points are where you want to re-project those source points into new plane.
The size of destination plane is:
width: 1000 pixels
height: 200 pixels
I just take the source rectangle width and height.
Image Used for the Perspective Transform
I used below image to do the perspective transform.

Code on Perspective Transform
Filename: Main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import os import cv2 as cv import numpy as np import matplotlib.pyplot as plt def perspectiveTransform(): root = os.getcwd() imgPath = os.path.join(root, 'images/restaurant.png') img = cv.imread(imgPath) img = cv.cvtColor(img, cv.COLOR_BGR2RGB) src = np.array([[477,539], [1476,748], [428,786], [1520,905]], dtype=np.float32) width = 1000 height = 200 dest = np.array([[0,0], [width,0], [0,height], [width,100]], dtype=np.float32) transformation = cv.getPerspectiveTransform(src, dest) warpedImg = cv.warpPerspective(img, transformation, (width, height)) plt.figure() plt.subplot(121) plt.imshow(img) plt.plot(src[:,0], src[:,1], 'r.') plt.subplot(122) plt.imshow(warpedImg) plt.plot(dest[:,0], dest[:,1], 'r.') plt.show() if __name__ == '__main__': print("Start") perspectiveTransform() |
To run the program, type at the terminal
1 |
python3 Main.py |
Folder Structure:
