Path: blob/master/modules/python/test/test_squares.py
16337 views
#!/usr/bin/env python12'''3Simple "Square Detector" program.45Loads several images sequentially and tries to find squares in each image.6'''78# Python 2/3 compatibility9import sys10PY3 = sys.version_info[0] == 31112if PY3:13xrange = range1415import numpy as np16import cv2 as cv171819def angle_cos(p0, p1, p2):20d1, d2 = (p0-p1).astype('float'), (p2-p1).astype('float')21return abs( np.dot(d1, d2) / np.sqrt( np.dot(d1, d1)*np.dot(d2, d2) ) )2223def find_squares(img):24img = cv.GaussianBlur(img, (5, 5), 0)25squares = []26for gray in cv.split(img):27for thrs in xrange(0, 255, 26):28if thrs == 0:29bin = cv.Canny(gray, 0, 50, apertureSize=5)30bin = cv.dilate(bin, None)31else:32_retval, bin = cv.threshold(gray, thrs, 255, cv.THRESH_BINARY)33contours, _hierarchy = cv.findContours(bin, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)34for cnt in contours:35cnt_len = cv.arcLength(cnt, True)36cnt = cv.approxPolyDP(cnt, 0.02*cnt_len, True)37if len(cnt) == 4 and cv.contourArea(cnt) > 1000 and cv.isContourConvex(cnt):38cnt = cnt.reshape(-1, 2)39max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)])40if max_cos < 0.1 and filterSquares(squares, cnt):41squares.append(cnt)4243return squares4445def intersectionRate(s1, s2):46area, _intersection = cv.intersectConvexConvex(np.array(s1), np.array(s2))47return 2 * area / (cv.contourArea(np.array(s1)) + cv.contourArea(np.array(s2)))4849def filterSquares(squares, square):5051for i in range(len(squares)):52if intersectionRate(squares[i], square) > 0.95:53return False5455return True5657from tests_common import NewOpenCVTests5859class squares_test(NewOpenCVTests):6061def test_squares(self):6263img = self.get_sample('samples/data/pic1.png')64squares = find_squares(img)6566testSquares = [67[[43, 25],68[43, 129],69[232, 129],70[232, 25]],7172[[252, 87],73[324, 40],74[387, 137],75[315, 184]],7677[[154, 178],78[196, 180],79[198, 278],80[154, 278]],8182[[0, 0],83[400, 0],84[400, 300],85[0, 300]]86]8788matches_counter = 089for i in range(len(squares)):90for j in range(len(testSquares)):91if intersectionRate(squares[i], testSquares[j]) > 0.9:92matches_counter += 19394self.assertGreater(matches_counter / len(testSquares), 0.9)95self.assertLess( (len(squares) - matches_counter) / len(squares), 0.2)9697if __name__ == '__main__':98NewOpenCVTests.bootstrap()99100101