test_squares.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #!/usr/bin/env python
  2. '''
  3. Simple "Square Detector" program.
  4. Loads several images sequentially and tries to find squares in each image.
  5. '''
  6. # Python 2/3 compatibility
  7. import sys
  8. PY3 = sys.version_info[0] == 3
  9. if PY3:
  10. xrange = range
  11. import numpy as np
  12. import cv2 as cv
  13. def 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. def find_squares(img):
  17. img = cv.GaussianBlur(img, (5, 5), 0)
  18. squares = []
  19. for gray in cv.split(img):
  20. for thrs in xrange(0, 255, 26):
  21. if thrs == 0:
  22. bin = cv.Canny(gray, 0, 50, apertureSize=5)
  23. bin = cv.dilate(bin, None)
  24. else:
  25. _retval, bin = cv.threshold(gray, thrs, 255, cv.THRESH_BINARY)
  26. contours, _hierarchy = cv.findContours(bin, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
  27. for cnt in contours:
  28. cnt_len = cv.arcLength(cnt, True)
  29. cnt = cv.approxPolyDP(cnt, 0.02*cnt_len, True)
  30. if len(cnt) == 4 and cv.contourArea(cnt) > 1000 and cv.isContourConvex(cnt):
  31. cnt = cnt.reshape(-1, 2)
  32. max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)])
  33. if max_cos < 0.1 and filterSquares(squares, cnt):
  34. squares.append(cnt)
  35. return squares
  36. def intersectionRate(s1, s2):
  37. area, _intersection = cv.intersectConvexConvex(np.array(s1), np.array(s2))
  38. return 2 * area / (cv.contourArea(np.array(s1)) + cv.contourArea(np.array(s2)))
  39. def filterSquares(squares, square):
  40. for i in range(len(squares)):
  41. if intersectionRate(squares[i], square) > 0.95:
  42. return False
  43. return True
  44. from tests_common import NewOpenCVTests
  45. class squares_test(NewOpenCVTests):
  46. def test_squares(self):
  47. img = self.get_sample('samples/data/pic1.png')
  48. squares = find_squares(img)
  49. testSquares = [
  50. [[43, 25],
  51. [43, 129],
  52. [232, 129],
  53. [232, 25]],
  54. [[252, 87],
  55. [324, 40],
  56. [387, 137],
  57. [315, 184]],
  58. [[154, 178],
  59. [196, 180],
  60. [198, 278],
  61. [154, 278]],
  62. [[0, 0],
  63. [400, 0],
  64. [400, 300],
  65. [0, 300]]
  66. ]
  67. matches_counter = 0
  68. for i in range(len(squares)):
  69. for j in range(len(testSquares)):
  70. if intersectionRate(squares[i], testSquares[j]) > 0.9:
  71. matches_counter += 1
  72. self.assertGreater(matches_counter / len(testSquares), 0.9)
  73. self.assertLess( (len(squares) - matches_counter) / len(squares), 0.2)
  74. if __name__ == '__main__':
  75. NewOpenCVTests.bootstrap()