floodfill.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #!/usr/bin/env python
  2. '''
  3. Floodfill sample.
  4. Usage:
  5. floodfill.py [<image>]
  6. Click on the image to set seed point
  7. Keys:
  8. f - toggle floating range
  9. c - toggle 4/8 connectivity
  10. ESC - exit
  11. '''
  12. # Python 2/3 compatibility
  13. from __future__ import print_function
  14. import numpy as np
  15. import cv2 as cv
  16. import sys
  17. class App():
  18. def update(self, dummy=None):
  19. if self.seed_pt is None:
  20. cv.imshow('floodfill', self.img)
  21. return
  22. flooded = self.img.copy()
  23. self.mask[:] = 0
  24. lo = cv.getTrackbarPos('lo', 'floodfill')
  25. hi = cv.getTrackbarPos('hi', 'floodfill')
  26. flags = self.connectivity
  27. if self.fixed_range:
  28. flags |= cv.FLOODFILL_FIXED_RANGE
  29. cv.floodFill(flooded, self.mask, self.seed_pt, (255, 255, 255), (lo,)*3, (hi,)*3, flags)
  30. cv.circle(flooded, self.seed_pt, 2, (0, 0, 255), -1)
  31. cv.imshow('floodfill', flooded)
  32. def onmouse(self, event, x, y, flags, param):
  33. if flags & cv.EVENT_FLAG_LBUTTON:
  34. self.seed_pt = x, y
  35. self.update()
  36. def run(self):
  37. try:
  38. fn = sys.argv[1]
  39. except:
  40. fn = 'fruits.jpg'
  41. self.img = cv.imread(cv.samples.findFile(fn))
  42. if self.img is None:
  43. print('Failed to load image file:', fn)
  44. sys.exit(1)
  45. h, w = self.img.shape[:2]
  46. self.mask = np.zeros((h+2, w+2), np.uint8)
  47. self.seed_pt = None
  48. self.fixed_range = True
  49. self.connectivity = 4
  50. self.update()
  51. cv.setMouseCallback('floodfill', self.onmouse)
  52. cv.createTrackbar('lo', 'floodfill', 20, 255, self.update)
  53. cv.createTrackbar('hi', 'floodfill', 20, 255, self.update)
  54. while True:
  55. ch = cv.waitKey()
  56. if ch == 27:
  57. break
  58. if ch == ord('f'):
  59. self.fixed_range = not self.fixed_range
  60. print('using %s range' % ('floating', 'fixed')[self.fixed_range])
  61. self.update()
  62. if ch == ord('c'):
  63. self.connectivity = 12-self.connectivity
  64. print('connectivity =', self.connectivity)
  65. self.update()
  66. print('Done')
  67. if __name__ == '__main__':
  68. print(__doc__)
  69. App().run()
  70. cv.destroyAllWindows()