Perspective Transformation in Python — on Live Video

Deepti Goyal
Analytics Vidhya
Published in
2 min readApr 7, 2020

Perspective Transform using Python OpenCV — In Perspective Transformation, we can change the perspective of a given image or video for getting better insights about the required information.

Image from Self-driving udacity course

In the below code we are doing the perspective transformation of a live video using OpenCV library of python

# Importing Librariesimport cv2
import numpy as np
from matplotlib import pyplot as plt
#Capturing video
cap = cv2.VideoCapture(0)
while True:
_,frame = cap.read()
# Plotting four circles on the video of the object you want to see the transformation of.
cv2.circle(frame,(114,151),5,(0,0,255),-1)
cv2.circle(frame, (605, 89), 5, (0, 0, 255), -1)
cv2.circle(frame, (72, 420), 5, (0, 0, 255), -1)
cv2.circle(frame, (637, 420), 5, (0, 0, 255), -1)
# selecting all the above four points in an array
imgPts = np.float32([[114,151],[605, 89],[72, 420],[637, 420]])

# selecting four points in an array for the destination video( the one you want to see as your output)
objPoints = np.float32([[0,0],[420,0],[0,637],[420,637]])
#Apply perspective transformation function of openCV2. This function will return the matrix which you can feed into warpPerspective function to get the warped image.
matrix = cv2.getPerspectiveTransform(imgPts,objPoints)
result = cv2.warpPerspective(frame,matrix,(400,600))
#Now Plotting both the videos(original, warped video)using matplotlib
cv2.imshow('frame',frame)
cv2.imshow('Perspective Transformation', result)
key = cv2.waitKey(1)
# plt.imshow(frame)
plt.show()
if key == 27:
break

cap.release()
cv2.destroyAllWindows()

Please let me know if this code was helpful.

Follow me on Github -https://github.com/DeeptiAgl?tab=repositories

--

--