-
Notifications
You must be signed in to change notification settings - Fork 0
/
AutoWarpPerspective.py
35 lines (31 loc) · 1.05 KB
/
AutoWarpPerspective.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
import cv2 as cv
import numpy as np
def click_event(event, x_cord, y_cord, flags, param):
global x, y
if event == cv.EVENT_LBUTTONDOWN:
x, y = x_cord, y_cord
img_path = 'cards.jpg'
x, y = -1, -1
pts1 = []
while len(pts1) < 4:
img = cv.imread(img_path)
cv.imshow('Clickable Image', img)
cv.setMouseCallback('Clickable Image', click_event)
if x > 0 and y > 0:
print(x, y)
pts1.append([x, y])
x, y = -1, -1
cv.waitKey(1)
cv.destroyAllWindows()
print(pts1)
img = cv.imread(img_path)
width = int(pow(pow(pts1[1][0] - pts1[0][0], 2) + pow(pts1[1][1] - pts1[0][1], 2), 0.5))
height = int(pow(pow(pts1[2][0] - pts1[1][0], 2) + pow(pts1[2][1] - pts1[1][1], 2), 0.5))
print(width, height)
pts1 = np.array(pts1, np.float32)
pts2 = np.array([[0, 0], [width, 0], [0, height], [width, height]], np.float32)
matrix = cv.getPerspectiveTransform(pts1, pts2)
output_img = cv.warpPerspective(img, matrix, (width, height))
cv.imshow('Warped Image', output_img)
cv.waitKey(0)
cv.destroyAllWindows()