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