opencv/samples/python2/distrans.py

72 lines
1.5 KiB
Python
Raw Normal View History

2013-03-06 14:41:02 +08:00
#!/usr/bin/env python
2012-10-17 07:18:30 +08:00
'''
Distance transform sample.
Usage:
distrans.py [<image>]
Keys:
ESC - exit
v - toggle voronoi mode
'''
# Python 2/3 compatibility
from __future__ import print_function
2012-10-17 07:18:30 +08:00
import numpy as np
import cv2
2013-03-06 14:41:02 +08:00
2012-10-17 07:18:30 +08:00
from common import make_cmap
if __name__ == '__main__':
import sys
2013-03-06 14:41:02 +08:00
try:
fn = sys.argv[1]
except:
2014-09-13 22:28:41 +08:00
fn = '../data/fruits.jpg'
print(__doc__)
2012-10-17 07:18:30 +08:00
img = cv2.imread(fn, 0)
2013-03-06 14:41:02 +08:00
if img is None:
print('Failed to load fn:', fn)
2013-03-06 14:41:02 +08:00
sys.exit(1)
2013-04-12 21:39:16 +08:00
2012-10-17 07:18:30 +08:00
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)
2013-04-12 21:39:16 +08:00
dist, labels = cv2.distanceTransformWithLabels(~mark, cv2.DIST_L2, 5)
2012-10-17 07:18:30 +08:00
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])
2012-10-17 07:18:30 +08:00
update()
if need_update:
update()
cv2.destroyAllWindows()