Skip to main content

Python : Warp Perspective using OpenCV

 In perspective transformation, the perspective of an image is tranformed to get a better view or insights about the required informatin. We need points of the image from which we want to gather information and also the points inside which we want to display our image.

In the example below, we will extract the visitor card from the image on the left and display it as shown in the right image.





# Warp Perspective
import opencv2

img = cv2.imread("opencv_resources/visitor_card.png")

# end-points of the image that we want to extract
# use tool like ms-paint to find the end points by placing your mouse cursor
# upper-left pt (point1), upper-right pt (point2), lower-left pt (point3), lower-right pt (point4)
pts1 = np.float32([[100,168], [555,60], [168,450], [667,282]])

# points to be mapped with the size of the extracted image i.e. map the points with 2D image 
width = 400
height = 200
pts2 = np.float32([[0,0], [width,0], [0,height], [width,height]])

# Transform perspective
matrix = cv2.getPerspectiveTransform(pts1,pts2)

# output image
out = cv2.warpPerspective(img,matrix,(width, height))

for i in range(0,4):
    cv2.circle(img, (pts1[i][0], pts1[i][1]), 4, (255,0,0), cv2.FILLED)

cv2.imshow("image1", img)
cv2.imshow("image2", out)
cv2.waitKey(0)

# Workaround for Jupyter Notebook to close the image
cv2.destroyAllWindows()
for i in range (1,5):
    cv2.waitKey(1)

Comments