squares.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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
  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 = cv2.GaussianBlur(img, (5, 5), 0)
  18. squares = []
  19. for gray in cv2.split(img):
  20. for thrs in xrange(0, 255, 26):
  21. if thrs == 0:
  22. bin = cv2.Canny(gray, 0, 50, apertureSize=5)
  23. bin = cv2.dilate(bin, None)
  24. else:
  25. retval, bin = cv2.threshold(gray, thrs, 255, cv2.THRESH_BINARY)
  26. bin, contours, hierarchy = cv2.findContours(bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
  27. for cnt in contours:
  28. cnt_len = cv2.arcLength(cnt, True)
  29. cnt = cv2.approxPolyDP(cnt, 0.02*cnt_len, True)
  30. if len(cnt) == 4 and cv2.contourArea(cnt) > 1000 and cv2.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:
  34. squares.append(cnt)
  35. return squares
  36. if __name__ == '__main__':
  37. from glob import glob
  38. for fn in glob('../data/pic*.png'):
  39. img = cv2.imread(fn)
  40. squares = find_squares(img)
  41. cv2.drawContours( img, squares, -1, (0, 255, 0), 3 )
  42. cv2.imshow('squares', img)
  43. ch = 0xFF & cv2.waitKey()
  44. if ch == 27:
  45. break
  46. cv2.destroyAllWindows()