We can change perspective in OpenCV using the functions cv2.getPerspectiveTransform(pts1,pts2) and cv2.warpPerspective(img,M,(640,480)). The cv2.getPerspectiveTransform() function calculates a perspective transform from four pairs of the corresponding points. The points pts1 and pts2 are two rectangles, where on is the source and the other the destination. Putting it together you get something like this:
1
2
3
4
5
6
7
|
def transform(img):
rows,cols = img.shape[:2]
pts1 = np.float32([[0,0],[300,-120],[0,300],[300,300]])
pts2 = np.float32([[100,0],[300,0],[100,200],[300,200]])
M = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(img,M,(640,480))
return dst
|
Which you can combine with any image input, such a video playing from the web:
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
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from cv2 import *
import cv2
import numpy as np
import matplotlib.pyplot as plt
def transform(img):
rows,cols = img.shape[:2]
pts1 = np.float32([[0,0],[300,-120],[0,300],[300,300]])
pts2 = np.float32([[100,0],[300,0],[100,200],[300,200]])
M = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(img,M,(640,480))
return dst
# Grab video
vc = cv2.VideoCapture('https://archive.org/download/bliptv-20131014-160024-Brigittedale-409WinkyHaHa665/bliptv-20131014-160024-Brigittedale-409WinkyHaHa665.mp4')
c=1
fps = 24
if vc.isOpened():
rval , frame = vc.read()
else:
rval = False
while rval:
rval, frame = vc.read()
dst = transform(frame)
cv2.imshow("Image", dst)
cv2.waitKey(1000 / fps);
vc.release()
|
Output: