samples/python/snippets/squares.py#

A n example using approxPolyDP function in python. *

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