-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathperspective_utils.py
65 lines (48 loc) · 1.97 KB
/
perspective_utils.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import numpy as np
import cv2
import glob
import matplotlib.pyplot as plt
from calibration_utils import calibrate_camera, undistort
from binarization_utils import binarize
def birdeye(img, verbose=False):
"""
Apply perspective transform to input frame to get the bird's eye view.
:param img: input color frame
:param verbose: if True, show the transformation result
:return: warped image, and both forward and backward transformation matrices
"""
h, w = img.shape[:2]
src = np.float32([[w, h-10], # br
[0, h-10], # bl
[546, 460], # tl
[732, 460]]) # tr
dst = np.float32([[w, h], # br
[0, h], # bl
[0, 0], # tl
[w, 0]]) # tr
M = cv2.getPerspectiveTransform(src, dst)
Minv = cv2.getPerspectiveTransform(dst, src)
warped = cv2.warpPerspective(img, M, (w, h), flags=cv2.INTER_LINEAR)
if verbose:
f, axarray = plt.subplots(1, 2)
f.set_facecolor('white')
axarray[0].set_title('Before perspective transform')
axarray[0].imshow(img, cmap='gray')
for point in src:
axarray[0].plot(*point, '.')
axarray[1].set_title('After perspective transform')
axarray[1].imshow(warped, cmap='gray')
for point in dst:
axarray[1].plot(*point, '.')
for axis in axarray:
axis.set_axis_off()
plt.show()
return warped, M, Minv
if __name__ == '__main__':
ret, mtx, dist, rvecs, tvecs = calibrate_camera(calib_images_dir='camera_cal')
# show result on test images
for test_img in glob.glob('test_images/*.jpg'):
img = cv2.imread(test_img)
img_undistorted = undistort(img, mtx, dist, verbose=False)
img_binary = binarize(img_undistorted, verbose=False)
img_birdeye, M, Minv = birdeye(cv2.cvtColor(img_undistorted, cv2.COLOR_BGR2RGB), verbose=True)