floodfill.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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
  16. if __name__ == '__main__':
  17. import sys
  18. try:
  19. fn = sys.argv[1]
  20. except:
  21. fn = '../data/fruits.jpg'
  22. print(__doc__)
  23. img = cv2.imread(fn, True)
  24. if img is None:
  25. print('Failed to load image file:', fn)
  26. sys.exit(1)
  27. h, w = img.shape[:2]
  28. mask = np.zeros((h+2, w+2), np.uint8)
  29. seed_pt = None
  30. fixed_range = True
  31. connectivity = 4
  32. def update(dummy=None):
  33. if seed_pt is None:
  34. cv2.imshow('floodfill', img)
  35. return
  36. flooded = img.copy()
  37. mask[:] = 0
  38. lo = cv2.getTrackbarPos('lo', 'floodfill')
  39. hi = cv2.getTrackbarPos('hi', 'floodfill')
  40. flags = connectivity
  41. if fixed_range:
  42. flags |= cv2.FLOODFILL_FIXED_RANGE
  43. cv2.floodFill(flooded, mask, seed_pt, (255, 255, 255), (lo,)*3, (hi,)*3, flags)
  44. cv2.circle(flooded, seed_pt, 2, (0, 0, 255), -1)
  45. cv2.imshow('floodfill', flooded)
  46. def onmouse(event, x, y, flags, param):
  47. global seed_pt
  48. if flags & cv2.EVENT_FLAG_LBUTTON:
  49. seed_pt = x, y
  50. update()
  51. update()
  52. cv2.setMouseCallback('floodfill', onmouse)
  53. cv2.createTrackbar('lo', 'floodfill', 20, 255, update)
  54. cv2.createTrackbar('hi', 'floodfill', 20, 255, update)
  55. while True:
  56. ch = 0xFF & cv2.waitKey()
  57. if ch == 27:
  58. break
  59. if ch == ord('f'):
  60. fixed_range = not fixed_range
  61. print('using %s range' % ('floating', 'fixed')[fixed_range])
  62. update()
  63. if ch == ord('c'):
  64. connectivity = 12-connectivity
  65. print('connectivity =', connectivity)
  66. update()
  67. cv2.destroyAllWindows()