watershed.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #!/usr/bin/env python
  2. '''
  3. Watershed segmentation
  4. =========
  5. This program demonstrates the watershed segmentation algorithm
  6. in OpenCV: watershed().
  7. Usage
  8. -----
  9. watershed.py [image filename]
  10. Keys
  11. ----
  12. 1-7 - switch marker color
  13. SPACE - update segmentation
  14. r - reset
  15. a - toggle autoupdate
  16. ESC - exit
  17. '''
  18. # Python 2/3 compatibility
  19. from __future__ import print_function
  20. import numpy as np
  21. import cv2 as cv
  22. from common import Sketcher
  23. class App:
  24. def __init__(self, fn):
  25. self.img = cv.imread(fn)
  26. if self.img is None:
  27. raise Exception('Failed to load image file: %s' % fn)
  28. h, w = self.img.shape[:2]
  29. self.markers = np.zeros((h, w), np.int32)
  30. self.markers_vis = self.img.copy()
  31. self.cur_marker = 1
  32. self.colors = np.int32( list(np.ndindex(2, 2, 2)) ) * 255
  33. self.auto_update = True
  34. self.sketch = Sketcher('img', [self.markers_vis, self.markers], self.get_colors)
  35. def get_colors(self):
  36. return list(map(int, self.colors[self.cur_marker])), self.cur_marker
  37. def watershed(self):
  38. m = self.markers.copy()
  39. cv.watershed(self.img, m)
  40. overlay = self.colors[np.maximum(m, 0)]
  41. vis = cv.addWeighted(self.img, 0.5, overlay, 0.5, 0.0, dtype=cv.CV_8UC3)
  42. cv.imshow('watershed', vis)
  43. def run(self):
  44. while cv.getWindowProperty('img', 0) != -1 or cv.getWindowProperty('watershed', 0) != -1:
  45. ch = cv.waitKey(50)
  46. if ch == 27:
  47. break
  48. if ch >= ord('1') and ch <= ord('7'):
  49. self.cur_marker = ch - ord('0')
  50. print('marker: ', self.cur_marker)
  51. if ch == ord(' ') or (self.sketch.dirty and self.auto_update):
  52. self.watershed()
  53. self.sketch.dirty = False
  54. if ch in [ord('a'), ord('A')]:
  55. self.auto_update = not self.auto_update
  56. print('auto_update if', ['off', 'on'][self.auto_update])
  57. if ch in [ord('r'), ord('R')]:
  58. self.markers[:] = 0
  59. self.markers_vis[:] = self.img
  60. self.sketch.show()
  61. cv.destroyAllWindows()
  62. if __name__ == '__main__':
  63. print(__doc__)
  64. import sys
  65. try:
  66. fn = sys.argv[1]
  67. except:
  68. fn = 'fruits.jpg'
  69. App(cv.samples.findFile(fn)).run()