opencv/samples/python2/watershed.py

65 lines
2.0 KiB
Python
Raw Normal View History

2011-07-01 23:09:38 +08:00
import numpy as np
import cv2
2011-07-02 01:33:29 +08:00
from common import Sketcher
2011-07-01 23:09:38 +08:00
help_message = '''
USAGE: watershed.py [<image>]
Use keys 1 - 7 to switch marker color
SPACE - update segmentation
r - reset
a - switch autoupdate
ESC - exit
'''
class App:
def __init__(self, fn):
self.img = cv2.imread(fn)
h, w = self.img.shape[:2]
self.markers = np.zeros((h, w), np.int32)
self.markers_vis = self.img.copy()
self.cur_marker = 1
self.colors = np.int32( list(np.ndindex(2, 2, 2)) ) * 255
self.auto_update = True
2011-07-02 01:33:29 +08:00
self.sketch = Sketcher('img', [self.markers_vis, self.markers], self.get_colors)
def get_colors(self):
return map(int, self.colors[self.cur_marker]), self.cur_marker
2011-07-01 23:09:38 +08:00
def watershed(self):
m = self.markers.copy()
cv2.watershed(self.img, m)
2011-07-04 22:13:57 +08:00
overlay = self.colors[np.maximum(m, 0)]
vis = cv2.addWeighted(self.img, 0.5, overlay, 0.5, 0.0, dtype=cv2.CV_8UC3)
2011-07-01 23:09:38 +08:00
cv2.imshow('watershed', vis)
def run(self):
while True:
ch = 0xFF & cv2.waitKey(50)
2011-07-01 23:09:38 +08:00
if ch == 27:
break
if ch >= ord('1') and ch <= ord('7'):
self.cur_marker = ch - ord('0')
print 'marker: ', self.cur_marker
2011-07-02 01:33:29 +08:00
if ch == ord(' ') or (self.sketch.dirty and self.auto_update):
2011-07-01 23:09:38 +08:00
self.watershed()
2011-07-02 01:33:29 +08:00
self.sketch.dirty = False
2011-07-01 23:09:38 +08:00
if ch in [ord('a'), ord('A')]:
self.auto_update = not self.auto_update
print 'auto_update if', ['off', 'on'][self.auto_update]
if ch in [ord('r'), ord('R')]:
2011-07-02 01:33:29 +08:00
self.markers[:] = 0
self.markers_vis[:] = self.img
2011-07-02 01:33:29 +08:00
self.sketch.show()
2012-03-15 11:45:15 +08:00
cv2.destroyAllWindows()
2011-07-01 23:09:38 +08:00
if __name__ == '__main__':
import sys
try: fn = sys.argv[1]
except: fn = '../cpp/fruits.jpg'
print help_message
App(fn).run()