Skip to content

Commit babe927

Browse files
committed
Added Perspective Transform
1 parent df053ed commit babe927

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed
997 KB
Loading
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import cv2
2+
import numpy as np
3+
import argparse
4+
5+
# global vars
6+
arr = []
7+
count = 0
8+
9+
# setup argparse
10+
parser = argparse.ArgumentParser()
11+
parser.add_argument("-p", "--path", help = "path to image")
12+
args = vars(parser.parse_args())
13+
14+
# transform image to perspective form using warpPerspective
15+
def transform(img, arr):
16+
(tl, tr, br, bl) = arr
17+
18+
# find the maximum width of selected object
19+
widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
20+
widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))
21+
w = max(int(widthA), int(widthB))
22+
23+
# find the maximum height of selected object
24+
heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
25+
heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))
26+
h = max(int(heightA), int(heightB))
27+
28+
# Create source and destination points
29+
inp_pts = np.float32(arr)
30+
op_pts = np.float32([[0,0],[w-1,0],[w-1,h-1],[0,h-1]])
31+
32+
# Create Perspective Transform and perform warp Perspective
33+
M = cv2.getPerspectiveTransform(inp_pts,op_pts)
34+
out = cv2.warpPerspective(img, M, (w, h))
35+
36+
return out
37+
38+
# read image
39+
img = cv2.imread(args["path"])
40+
41+
# resize image
42+
width = 500
43+
height = int((img.shape[0] * 500)/(img.shape[1]))
44+
dim = (width, height)
45+
img = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
46+
47+
cv2.imshow('image', img)
48+
49+
# helper function to append coordinates
50+
def points(x,y):
51+
if len(arr) <= 4:
52+
arr.append((x,y))
53+
return len(arr)
54+
55+
# helper function to draw connector lines
56+
def draw(count, img):
57+
if(count == 2):
58+
cv2.line(img, arr[0], arr[1], (255,255,255), 2)
59+
if(count == 3):
60+
cv2.line(img, arr[1], arr[2], (255,255,255), 2)
61+
if(count == 4):
62+
cv2.line(img, arr[2], arr[3], (255,255,255), 2)
63+
cv2.line(img, arr[3], arr[0], (255,255,255), 2)
64+
65+
# mouseclick events
66+
def onClick(event, x, y, flags, param):
67+
if event == cv2.EVENT_LBUTTONDOWN:
68+
count = points(x,y)
69+
if count <= 4:
70+
cv2.circle(img, (x,y), 2, (255,255,0), 10)
71+
draw(count, img)
72+
cv2.imshow('image', img)
73+
74+
cv2.setMouseCallback('image', onClick)
75+
cv2.waitKey(0)
76+
77+
# transform image with mentioned coordinates
78+
out = transform(img, arr)
79+
80+
cv2.imshow('final', out)
81+
cv2.waitKey(0)
82+
cv2.destroyAllWindows()

0 commit comments

Comments
 (0)