contours.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/env python
  2. '''
  3. This program illustrates the use of findContours and drawContours.
  4. The original image is put up along with the image of drawn contours.
  5. Usage:
  6. contours.py
  7. A trackbar is put up which controls the contour level from -3 to 3
  8. '''
  9. # Python 2/3 compatibility
  10. from __future__ import print_function
  11. import sys
  12. PY3 = sys.version_info[0] == 3
  13. if PY3:
  14. xrange = range
  15. import numpy as np
  16. import cv2 as cv
  17. def make_image():
  18. img = np.zeros((500, 500), np.uint8)
  19. black, white = 0, 255
  20. for i in xrange(6):
  21. dx = int((i%2)*250 - 30)
  22. dy = int((i/2.)*150)
  23. if i == 0:
  24. for j in xrange(11):
  25. angle = (j+5)*np.pi/21
  26. c, s = np.cos(angle), np.sin(angle)
  27. x1, y1 = np.int32([dx+100+j*10-80*c, dy+100-90*s])
  28. x2, y2 = np.int32([dx+100+j*10-30*c, dy+100-30*s])
  29. cv.line(img, (x1, y1), (x2, y2), white)
  30. cv.ellipse( img, (dx+150, dy+100), (100,70), 0, 0, 360, white, -1 )
  31. cv.ellipse( img, (dx+115, dy+70), (30,20), 0, 0, 360, black, -1 )
  32. cv.ellipse( img, (dx+185, dy+70), (30,20), 0, 0, 360, black, -1 )
  33. cv.ellipse( img, (dx+115, dy+70), (15,15), 0, 0, 360, white, -1 )
  34. cv.ellipse( img, (dx+185, dy+70), (15,15), 0, 0, 360, white, -1 )
  35. cv.ellipse( img, (dx+115, dy+70), (5,5), 0, 0, 360, black, -1 )
  36. cv.ellipse( img, (dx+185, dy+70), (5,5), 0, 0, 360, black, -1 )
  37. cv.ellipse( img, (dx+150, dy+100), (10,5), 0, 0, 360, black, -1 )
  38. cv.ellipse( img, (dx+150, dy+150), (40,10), 0, 0, 360, black, -1 )
  39. cv.ellipse( img, (dx+27, dy+100), (20,35), 0, 0, 360, white, -1 )
  40. cv.ellipse( img, (dx+273, dy+100), (20,35), 0, 0, 360, white, -1 )
  41. return img
  42. def main():
  43. img = make_image()
  44. h, w = img.shape[:2]
  45. contours0, hierarchy = cv.findContours( img.copy(), cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
  46. contours = [cv.approxPolyDP(cnt, 3, True) for cnt in contours0]
  47. def update(levels):
  48. vis = np.zeros((h, w, 3), np.uint8)
  49. levels = levels - 3
  50. cv.drawContours( vis, contours, (-1, 2)[levels <= 0], (128,255,255),
  51. 3, cv.LINE_AA, hierarchy, abs(levels) )
  52. cv.imshow('contours', vis)
  53. update(3)
  54. cv.createTrackbar( "levels+3", "contours", 3, 7, update )
  55. cv.imshow('image', img)
  56. cv.waitKey()
  57. print('Done')
  58. if __name__ == '__main__':
  59. print(__doc__)
  60. main()
  61. cv.destroyAllWindows()