distrans.py sample added

This commit is contained in:
Alexander Mordvintsev 2011-07-02 22:21:19 +00:00
parent 724cc5b481
commit d3da43c8e5
3 changed files with 82 additions and 1 deletions

View File

@ -83,3 +83,29 @@ class Sketcher:
self.show()
else:
self.prev_pt = None
# palette data from matplotlib/_cm.py
_jet_data = {'red': ((0., 0, 0), (0.35, 0, 0), (0.66, 1, 1), (0.89,1, 1),
(1, 0.5, 0.5)),
'green': ((0., 0, 0), (0.125,0, 0), (0.375,1, 1), (0.64,1, 1),
(0.91,0,0), (1, 0, 0)),
'blue': ((0., 0.5, 0.5), (0.11, 1, 1), (0.34, 1, 1), (0.65,0, 0),
(1, 0, 0))}
cmap_data = { 'jet' : _jet_data }
def make_cmap(name, n=256):
data = cmap_data[name]
xs = np.linspace(0.0, 1.0, n)
channels = []
eps = 1e-6
for ch_name in ['blue', 'green', 'red']:
ch_data = data[ch_name]
xp, yp = [], []
for x, y1, y2 in ch_data:
xp += [x, x+eps]
yp += [y1, y2]
ch = np.interp(xs, xp, yp)
channels.append(ch)
return np.uint8(np.array(channels).T*255)

View File

@ -0,0 +1,55 @@
import numpy as np
import cv2, cv
from common import make_cmap
help_message = '''USAGE: distrans.py [<image>]
Keys:
ESC - exit
v - toggle voronoi mode
'''
if __name__ == '__main__':
import sys
try: fn = sys.argv[1]
except: fn = '../cpp/fruits.jpg'
print help_message
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.distanceTransform(~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 = cv2.waitKey(50)
if ch == 27:
break
if ch == ord('v'):
voronoi = not voronoi
print 'showing', ['distance', 'voronoi'][voronoi]
update()
if need_update:
update()

View File

@ -18,7 +18,7 @@ while True:
gray = cv2.cvtColor(img, cv.CV_BGR2GRAY)
thrs1 = cv2.getTrackbarPos('thrs1', 'edge')
thrs2 = cv2.getTrackbarPos('thrs2', 'edge')
edge = cv2.canny(gray, thrs1, thrs2, apertureSize=5)
edge = cv2.Canny(gray, thrs1, thrs2, apertureSize=5)
vis = img.copy()
vis /= 2
vis[edge != 0] = (0, 255, 0)