File: distrans.py

package info (click to toggle)
opencv 2.4.9.1%2Bdfsg-1%2Bdeb8u1
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 126,800 kB
  • ctags: 62,729
  • sloc: xml: 509,055; cpp: 490,794; lisp: 23,208; python: 21,174; java: 19,317; ansic: 1,038; sh: 128; makefile: 72
file content (63 lines) | stat: -rwxr-xr-x 1,401 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env python

'''
Distance transform sample.

Usage:
  distrans.py [<image>]

Keys:
  ESC   - exit
  v     - toggle voronoi mode
'''


import numpy as np
import cv2
import cv2.cv as cv
from common import make_cmap

if __name__ == '__main__':
    import sys
    try: fn = sys.argv[1]
    except: fn = '../cpp/fruits.jpg'
    print __doc__

    img = cv2.imread(fn, 0)
    cm = make_cmap('jet')
    need_update = True
    voronoi = False

    def update(dummy=None):
        global need_update
        need_update = False
        thrs = cv2.getTrackbarPos('threshold', 'distrans')
        mark = cv2.Canny(img, thrs, 3*thrs)
        dist, labels = cv2.distanceTransformWithLabels(~mark, cv.CV_DIST_L2, 5)
        if voronoi:
            vis = cm[np.uint8(labels)]
        else:
            vis = cm[np.uint8(dist*2)]
        vis[mark != 0] = 255
        cv2.imshow('distrans', vis)

    def invalidate(dummy=None):
        global need_update
        need_update = True

    cv2.namedWindow('distrans')
    cv2.createTrackbar('threshold', 'distrans', 60, 255, invalidate)
    update()


    while True:
        ch = 0xFF & cv2.waitKey(50)
        if ch == 27:
            break
        if ch == ord('v'):
            voronoi = not voronoi
            print 'showing', ['distance', 'voronoi'][voronoi]
            update()
        if need_update:
            update()
    cv2.destroyAllWindows()