Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/python/squares.py
16337 views
1
#!/usr/bin/env python
2
3
'''
4
Simple "Square Detector" program.
5
6
Loads several images sequentially and tries to find squares in each image.
7
'''
8
9
# Python 2/3 compatibility
10
import sys
11
PY3 = sys.version_info[0] == 3
12
13
if PY3:
14
xrange = range
15
16
import numpy as np
17
import cv2 as cv
18
19
20
def angle_cos(p0, p1, p2):
21
d1, d2 = (p0-p1).astype('float'), (p2-p1).astype('float')
22
return abs( np.dot(d1, d2) / np.sqrt( np.dot(d1, d1)*np.dot(d2, d2) ) )
23
24
def find_squares(img):
25
img = cv.GaussianBlur(img, (5, 5), 0)
26
squares = []
27
for gray in cv.split(img):
28
for thrs in xrange(0, 255, 26):
29
if thrs == 0:
30
bin = cv.Canny(gray, 0, 50, apertureSize=5)
31
bin = cv.dilate(bin, None)
32
else:
33
_retval, bin = cv.threshold(gray, thrs, 255, cv.THRESH_BINARY)
34
bin, contours, _hierarchy = cv.findContours(bin, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
35
for cnt in contours:
36
cnt_len = cv.arcLength(cnt, True)
37
cnt = cv.approxPolyDP(cnt, 0.02*cnt_len, True)
38
if len(cnt) == 4 and cv.contourArea(cnt) > 1000 and cv.isContourConvex(cnt):
39
cnt = cnt.reshape(-1, 2)
40
max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)])
41
if max_cos < 0.1:
42
squares.append(cnt)
43
return squares
44
45
if __name__ == '__main__':
46
from glob import glob
47
for fn in glob('../data/pic*.png'):
48
img = cv.imread(fn)
49
squares = find_squares(img)
50
cv.drawContours( img, squares, -1, (0, 255, 0), 3 )
51
cv.imshow('squares', img)
52
ch = cv.waitKey()
53
if ch == 27:
54
break
55
cv.destroyAllWindows()
56
57