-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfour_point_transform.py
67 lines (55 loc) · 2.66 KB
/
four_point_transform.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
64
65
66
67
# https://www.pyimagesearch.com/2014/08/25/4-point-opencv-getperspective-transform-example/
# import the necessary packages
import numpy as np
import cv2
def order_points(points):
# initialize a list of coordinates that will be ordered
# such that the first entry in the list is the top-left,
# the second entry is the top-right, the third is the
# bottom-right, and the fourth is the bottom-left
rectangle = np.zeros((4, 2), dtype="float32")
# the top-left point will have the smallest sum, whereas
# the bottom-right point will have the largest sum
s = points.sum(axis=1)
rectangle[0] = points[np.argmin(s)]
rectangle[2] = points[np.argmax(s)]
# now, compute the difference between the points, the
# top-right point will have the smallest difference,
# whereas the bottom-left will have the largest difference
diff = np.diff(points, axis=1)
rectangle[1] = points[np.argmin(diff)]
rectangle[3] = points[np.argmax(diff)]
# return the ordered coordinates
return rectangle
def four_point_transform(image, points):
# obtain a consistent order of the points and unpack them
# individually
rectangle = order_points(points)
(tl, tr, br, bl) = rectangle
# compute the width of the new image, which will be the
# maximum distance between bottom-right and bottom-left
# x-co-ordinates or the top-right and top-left x-coordinates
width_a = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
width_b = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))
max_width = max(int(width_a), int(width_b))
# compute the height of the new image, which will be the
# maximum distance between the top-right and bottom-right
# y-coordinates or the top-left and bottom-left y-coordinates
height_a = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
height_b = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))
max_height = max(int(height_a), int(height_b))
# now that we have the dimensions of the new image, construct
# the set of destination points to obtain a "birds eye view",
# (i.e. top-down view) of the image, again specifying points
# in the top-left, top-right, bottom-right, and bottom-left
# order
dst = np.array([
[0, 0],
[max_width - 1, 0],
[max_width - 1, max_height - 1],
[0, max_height - 1]], dtype="float32")
# compute the perspective transform matrix and then apply it
perspective_transform_matrix = cv2.getPerspectiveTransform(rectangle, dst)
warped = cv2.warpPerspective(image, perspective_transform_matrix, (max_width, max_height))
# return the warped image
return warped