distrans.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 as cv
  14. from common import make_cmap
  15. def main():
  16. import sys
  17. try:
  18. fn = sys.argv[1]
  19. except:
  20. fn = 'fruits.jpg'
  21. fn = cv.samples.findFile(fn)
  22. img = cv.imread(fn, cv.IMREAD_GRAYSCALE)
  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 = cv.getTrackbarPos('threshold', 'distrans')
  33. mark = cv.Canny(img, thrs, 3*thrs)
  34. dist, labels = cv.distanceTransformWithLabels(~mark, cv.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. cv.imshow('distrans', vis)
  41. def invalidate(dummy=None):
  42. global need_update
  43. need_update = True
  44. cv.namedWindow('distrans')
  45. cv.createTrackbar('threshold', 'distrans', 60, 255, invalidate)
  46. update()
  47. while True:
  48. ch = cv.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. print('Done')
  58. if __name__ == '__main__':
  59. print(__doc__)
  60. main()
  61. cv.destroyAllWindows()