7 This program demonstrates the watershed segmentation algorithm
8 in OpenCV: watershed().
12 watershed.py [image filename]
16 1-7 - switch marker color
17 SPACE - update segmentation
25 # Python 2/3 compatibility
26 from __future__ import print_function
30 from common import Sketcher
33 def __init__(self, fn):
34 self.img = cv.imread(fn)
36 raise Exception('Failed to load image file: %s' % fn)
38 h, w = self.img.shape[:2]
39 self.markers = np.zeros((h, w), np.int32)
40 self.markers_vis = self.img.copy()
42 self.colors = np.int32( list(np.ndindex(2, 2, 2)) ) * 255
44 self.auto_update = True
45 self.sketch = Sketcher('img', [self.markers_vis, self.markers], self.get_colors)
48 return list(map(int, self.colors[self.cur_marker])), self.cur_marker
51 m = self.markers.copy()
52 cv.watershed(self.img, m)
53 overlay = self.colors[np.maximum(m, 0)]
54 vis = cv.addWeighted(self.img, 0.5, overlay, 0.5, 0.0, dtype=cv.CV_8UC3)
55 cv.imshow('watershed', vis)
58 while cv.getWindowProperty('img', 0) != -1 or cv.getWindowProperty('watershed', 0) != -1:
62 if ch >= ord('1') and ch <= ord('7'):
63 self.cur_marker = ch - ord('0')
64 print('marker: ', self.cur_marker)
65 if ch == ord(' ') or (self.sketch.dirty and self.auto_update):
67 self.sketch.dirty = False
68 if ch in [ord('a'), ord('A')]:
69 self.auto_update = not self.auto_update
70 print('auto_update if', ['off', 'on'][self.auto_update])
71 if ch in [ord('r'), ord('R')]:
73 self.markers_vis[:] = self.img
75 cv.destroyAllWindows()
78 if __name__ == '__main__':
85 App(cv.samples.findFile(fn)).run()