squares.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. from __future__ import print_function
  8. import sys
  9. PY3 = sys.version_info[0] == 3
  10. if PY3:
  11. xrange = range
  12. import numpy as np
  13. import cv2 as cv
  14. def angle_cos(p0, p1, p2):
  15. d1, d2 = (p0-p1).astype('float'), (p2-p1).astype('float')
  16. return abs( np.dot(d1, d2) / np.sqrt( np.dot(d1, d1)*np.dot(d2, d2) ) )
  17. def find_squares(img):
  18. img = cv.GaussianBlur(img, (5, 5), 0)
  19. squares = []
  20. for gray in cv.split(img):
  21. for thrs in xrange(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 xrange(4)])
  34. if max_cos < 0.1:
  35. squares.append(cnt)
  36. return squares
  37. def main():
  38. from glob import glob
  39. for fn in glob('../data/pic*.png'):
  40. img = cv.imread(fn)
  41. squares = find_squares(img)
  42. cv.drawContours( img, squares, -1, (0, 255, 0), 3 )
  43. cv.imshow('squares', img)
  44. ch = cv.waitKey()
  45. if ch == 27:
  46. break
  47. print('Done')
  48. if __name__ == '__main__':
  49. print(__doc__)
  50. main()
  51. cv.destroyAllWindows()