-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPerspectiveTransformation.py
50 lines (42 loc) · 1.96 KB
/
PerspectiveTransformation.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
import cv2
import numpy as np
class PerspectiveTransformation:
""" This a class for transforming image between front view and top view
Attributes:
src (np.array): Coordinates of 4 source points
dst (np.array): Coordinates of 4 destination points
M (np.array): Matrix to transform image from front view to top view
M_inv (np.array): Matrix to transform image from top view to front view
"""
def __init__(self):
"""Init PerspectiveTransformation."""
self.src = np.float32([(550, 460), # top-left
(150, 720), # bottom-left
(1200, 720), # bottom-right
(770, 460)]) # top-right
self.dst = np.float32([(100, 0),
(100, 720),
(1100, 720),
(1100, 0)])
self.M = cv2.getPerspectiveTransform(self.src, self.dst)
self.M_inv = cv2.getPerspectiveTransform(self.dst, self.src)
def forward(self, img, img_size=(1280, 720), flags=cv2.INTER_LINEAR):
""" Take a front view image and transform to top view
Parameters:
img (np.array): A front view image
img_size (tuple): Size of the image (width, height)
flags : flag to use in cv2.warpPerspective()
Returns:
Image (np.array): Top view image
"""
return cv2.warpPerspective(img, self.M, img_size, flags=flags)
def backward(self, img, img_size=(1280, 720), flags=cv2.INTER_LINEAR):
""" Take a top view image and transform it to front view
Parameters:
img (np.array): A top view image
img_size (tuple): Size of the image (width, height)
flags (int): flag to use in cv2.warpPerspective()
Returns:
Image (np.array): Front view image
"""
return cv2.warpPerspective(img, self.M_inv, img_size, flags=flags)