distrans.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/env python
  2. '''
  3. Distance transform sample.
  4. Usage:
  5. distrans.py [<image>]
  6. Keys:
  7. ESC - exit
  8. v - toggle voronoi mode
  9. '''
  10. # Python 2/3 compatibility
  11. from __future__ import print_function
  12. import numpy as np
  13. import cv2
  14. from common import make_cmap
  15. if __name__ == '__main__':
  16. import sys
  17. try:
  18. fn = sys.argv[1]
  19. except:
  20. fn = '../data/fruits.jpg'
  21. print(__doc__)
  22. img = cv2.imread(fn, 0)
  23. if img is None:
  24. print('Failed to load fn:', fn)
  25. sys.exit(1)
  26. cm = make_cmap('jet')
  27. need_update = True
  28. voronoi = False
  29. def update(dummy=None):
  30. global need_update
  31. need_update = False
  32. thrs = cv2.getTrackbarPos('threshold', 'distrans')
  33. mark = cv2.Canny(img, thrs, 3*thrs)
  34. dist, labels = cv2.distanceTransformWithLabels(~mark, cv2.DIST_L2, 5)
  35. if voronoi:
  36. vis = cm[np.uint8(labels)]
  37. else:
  38. vis = cm[np.uint8(dist*2)]
  39. vis[mark != 0] = 255
  40. cv2.imshow('distrans', vis)
  41. def invalidate(dummy=None):
  42. global need_update
  43. need_update = True
  44. cv2.namedWindow('distrans')
  45. cv2.createTrackbar('threshold', 'distrans', 60, 255, invalidate)
  46. update()
  47. while True:
  48. ch = 0xFF & cv2.waitKey(50)
  49. if ch == 27:
  50. break
  51. if ch == ord('v'):
  52. voronoi = not voronoi
  53. print('showing', ['distance', 'voronoi'][voronoi])
  54. update()
  55. if need_update:
  56. update()
  57. cv2.destroyAllWindows()