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