2013-03-06 14:41:02 +08:00
|
|
|
#!/usr/bin/env python
|
2012-11-24 02:57:22 +08:00
|
|
|
|
2012-10-17 07:18:30 +08:00
|
|
|
'''
|
|
|
|
Distance transform sample.
|
|
|
|
|
|
|
|
Usage:
|
|
|
|
distrans.py [<image>]
|
|
|
|
|
|
|
|
Keys:
|
|
|
|
ESC - exit
|
|
|
|
v - toggle voronoi mode
|
|
|
|
'''
|
|
|
|
|
2015-09-14 00:00:22 +08:00
|
|
|
# Python 2/3 compatibility
|
|
|
|
from __future__ import print_function
|
2012-10-17 07:18:30 +08:00
|
|
|
|
|
|
|
import numpy as np
|
2017-12-11 17:55:03 +08:00
|
|
|
import cv2 as cv
|
2013-03-06 14:41:02 +08:00
|
|
|
|
2012-10-17 07:18:30 +08:00
|
|
|
from common import make_cmap
|
|
|
|
|
2019-03-20 02:03:58 +08:00
|
|
|
def main():
|
2012-10-17 07:18:30 +08:00
|
|
|
import sys
|
2013-03-06 14:41:02 +08:00
|
|
|
try:
|
|
|
|
fn = sys.argv[1]
|
|
|
|
except:
|
2018-11-14 23:56:21 +08:00
|
|
|
fn = 'fruits.jpg'
|
2012-10-17 07:18:30 +08:00
|
|
|
|
2018-11-14 23:56:21 +08:00
|
|
|
fn = cv.samples.findFile(fn)
|
|
|
|
img = cv.imread(fn, cv.IMREAD_GRAYSCALE)
|
2013-03-06 14:41:02 +08:00
|
|
|
if img is None:
|
2015-09-14 00:00:22 +08:00
|
|
|
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
|
2017-12-11 17:55:03 +08:00
|
|
|
thrs = cv.getTrackbarPos('threshold', 'distrans')
|
|
|
|
mark = cv.Canny(img, thrs, 3*thrs)
|
|
|
|
dist, labels = cv.distanceTransformWithLabels(~mark, cv.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
|
2017-12-11 17:55:03 +08:00
|
|
|
cv.imshow('distrans', vis)
|
2012-10-17 07:18:30 +08:00
|
|
|
|
|
|
|
def invalidate(dummy=None):
|
|
|
|
global need_update
|
|
|
|
need_update = True
|
|
|
|
|
2017-12-11 17:55:03 +08:00
|
|
|
cv.namedWindow('distrans')
|
|
|
|
cv.createTrackbar('threshold', 'distrans', 60, 255, invalidate)
|
2012-10-17 07:18:30 +08:00
|
|
|
update()
|
|
|
|
|
|
|
|
|
|
|
|
while True:
|
2017-12-11 17:55:03 +08:00
|
|
|
ch = cv.waitKey(50)
|
2012-10-17 07:18:30 +08:00
|
|
|
if ch == 27:
|
|
|
|
break
|
|
|
|
if ch == ord('v'):
|
|
|
|
voronoi = not voronoi
|
2015-09-14 00:00:22 +08:00
|
|
|
print('showing', ['distance', 'voronoi'][voronoi])
|
2012-10-17 07:18:30 +08:00
|
|
|
update()
|
|
|
|
if need_update:
|
|
|
|
update()
|
2019-03-20 02:03:58 +08:00
|
|
|
|
|
|
|
print('Done')
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
print(__doc__)
|
|
|
|
main()
|
2017-12-11 17:55:03 +08:00
|
|
|
cv.destroyAllWindows()
|