cv2 polygon to rect

Solutions on MaxInterview for cv2 polygon to rect by the best coders in the world

showing results for - "cv2 polygon to rect"
Josué
09 Mar 2019
1import numpy as np
2import cv2
3
4def order_points(pts):
5	# initialzie a list of coordinates that will be ordered
6	# such that the first entry in the list is the top-left,
7	# the second entry is the top-right, the third is the
8	# bottom-right, and the fourth is the bottom-left
9	rect = np.zeros((4, 2), dtype = "float32")
10	# the top-left point will have the smallest sum, whereas
11	# the bottom-right point will have the largest sum
12	s = pts.sum(axis = 1)
13	rect[0] = pts[np.argmin(s)]
14	rect[2] = pts[np.argmax(s)]
15	# now, compute the difference between the points, the
16	# top-right point will have the smallest difference,
17	# whereas the bottom-left will have the largest difference
18	diff = np.diff(pts, axis = 1)
19	rect[1] = pts[np.argmin(diff)]
20	rect[3] = pts[np.argmax(diff)]
21	# return the ordered coordinates
22	return rect
23   
24def four_point_transform(image, pts):
25	# obtain a consistent order of the points and unpack them
26	# individually
27	rect = order_points(pts)
28	(tl, tr, br, bl) = rect
29	# compute the width of the new image, which will be the
30	# maximum distance between bottom-right and bottom-left
31	# x-coordiates or the top-right and top-left x-coordinates
32	widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
33	widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))
34	maxWidth = max(int(widthA), int(widthB))
35	# compute the height of the new image, which will be the
36	# maximum distance between the top-right and bottom-right
37	# y-coordinates or the top-left and bottom-left y-coordinates
38	heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
39	heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))
40	maxHeight = max(int(heightA), int(heightB))
41	# now that we have the dimensions of the new image, construct
42	# the set of destination points to obtain a "birds eye view",
43	# (i.e. top-down view) of the image, again specifying points
44	# in the top-left, top-right, bottom-right, and bottom-left
45	# order
46	dst = np.array([
47		[0, 0],
48		[maxWidth - 1, 0],
49		[maxWidth - 1, maxHeight - 1],
50		[0, maxHeight - 1]], dtype = "float32")
51	# compute the perspective transform matrix and then apply it
52	M = cv2.getPerspectiveTransform(rect, dst)
53	warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))
54	# return the warped image
55	return warped