Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/python/distrans.py
16337 views
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
# Python 2/3 compatibility
15
from __future__ import print_function
16
17
import numpy as np
18
import cv2 as cv
19
20
from common import make_cmap
21
22
if __name__ == '__main__':
23
import sys
24
try:
25
fn = sys.argv[1]
26
except:
27
fn = '../data/fruits.jpg'
28
print(__doc__)
29
30
img = cv.imread(fn, 0)
31
if img is None:
32
print('Failed to load fn:', fn)
33
sys.exit(1)
34
35
cm = make_cmap('jet')
36
need_update = True
37
voronoi = False
38
39
def update(dummy=None):
40
global need_update
41
need_update = False
42
thrs = cv.getTrackbarPos('threshold', 'distrans')
43
mark = cv.Canny(img, thrs, 3*thrs)
44
dist, labels = cv.distanceTransformWithLabels(~mark, cv.DIST_L2, 5)
45
if voronoi:
46
vis = cm[np.uint8(labels)]
47
else:
48
vis = cm[np.uint8(dist*2)]
49
vis[mark != 0] = 255
50
cv.imshow('distrans', vis)
51
52
def invalidate(dummy=None):
53
global need_update
54
need_update = True
55
56
cv.namedWindow('distrans')
57
cv.createTrackbar('threshold', 'distrans', 60, 255, invalidate)
58
update()
59
60
61
while True:
62
ch = cv.waitKey(50)
63
if ch == 27:
64
break
65
if ch == ord('v'):
66
voronoi = not voronoi
67
print('showing', ['distance', 'voronoi'][voronoi])
68
update()
69
if need_update:
70
update()
71
cv.destroyAllWindows()
72
73