-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetRectangle.py
More file actions
91 lines (58 loc) · 1.8 KB
/
Copy pathgetRectangle.py
File metadata and controls
91 lines (58 loc) · 1.8 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import cv2
import time
import saveImage
import numpy as np
DELAY = 0.02
IS_FOUND = 0
MORPH = 7
CANNY = 250
_width = 600.0
_height = 420.0
_margin = 0.0
video_capture = cv2.VideoCapture(0)
corners = np.array(
[
[[ _margin, _margin ]],
[[ _margin, _height + _margin ]],
[[ _width + _margin, _height + _margin ]],
[[ _width + _margin, _margin ]],
]
)
pts_dst = np.array( corners, np.float32 )
while True :
ret, rgb = video_capture.read()
if ( ret ):
gray = cv2.cvtColor( rgb, cv2.COLOR_BGR2GRAY )
gray = cv2.bilateralFilter( gray, 1, 10, 120 )
edges = cv2.Canny( gray, 10, CANNY )
kernel = cv2.getStructuringElement( cv2.MORPH_RECT, ( MORPH, MORPH ) )
closed = cv2.morphologyEx( edges, cv2.MORPH_CLOSE, kernel )
contours, h = cv2.findContours( closed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE )
for cont in contours:
if cv2.contourArea( cont ) > 5000 :
arc_len = cv2.arcLength( cont, True )
approx = cv2.approxPolyDP( cont, 0.1 * arc_len, True )
if ( len( approx ) == 4 ):
IS_FOUND = 1
pts_src = np.array( approx, np.float32 )
h, status = cv2.findHomography( pts_src, pts_dst )
out = cv2.warpPerspective( rgb, h, ( int( _width + _margin * 2 ), int( _height + _margin * 2 ) ) )
cv2.drawContours( rgb, [approx], -1, ( 255, 0, 0 ), 2 )
else : pass
cv2.namedWindow( 'edges', cv2.CV_WINDOW_AUTOSIZE )
cv2.imshow( 'edges', edges )
cv2.namedWindow( 'rgb', cv2.CV_WINDOW_AUTOSIZE )
cv2.imshow( 'rgb', rgb )
if IS_FOUND :
cv2.namedWindow( 'out', cv2.CV_WINDOW_AUTOSIZE )
cv2.imshow( 'out', out )
if cv2.waitKey(27) & 0xFF == ord('q') :
break
if cv2.waitKey(99) & 0xFF == ord('c') :
saveImage.saveImage(out)
time.sleep( DELAY )
else :
print "Stopped"
break
video_capture.release()
cv2.destroyAllWindows()