floodfill.py 1.84 KB
Newer Older
1
import numpy as np
2
import cv2
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

help_message = '''USAGE: floodfill.py [<image>]

Click on the image to set seed point

Keys:
  f     - toggle floating range
  c     - toggle 4/8 connectivity
  ESC   - exit
'''

if __name__ == '__main__':
    import sys
    try: fn = sys.argv[1]
    except: fn = '../cpp/fruits.jpg'
    print help_message

    img = cv2.imread(fn, True)
    h, w = img.shape[:2]
    mask = np.zeros((h+2, w+2), np.uint8)
    seed_pt = None
    fixed_range = True
    connectivity = 4

    def update(dummy=None):
        if seed_pt is None:
            cv2.imshow('floodfill', img)
            return
        flooded = img.copy()
        mask[:] = 0
        lo = cv2.getTrackbarPos('lo', 'floodfill')
        hi = cv2.getTrackbarPos('hi', 'floodfill')
        flags = connectivity
        if fixed_range:
            flags |= cv2.FLOODFILL_FIXED_RANGE
        cv2.floodFill(flooded, mask, seed_pt, (255, 255, 255), (lo,)*3, (hi,)*3, flags)
        cv2.circle(flooded, seed_pt, 2, (0, 0, 255), -1)
        cv2.imshow('floodfill', flooded)

    def onmouse(event, x, y, flags, param):
        global seed_pt
44
        if flags & cv2.EVENT_FLAG_LBUTTON:
45 46 47 48 49 50 51 52 53
            seed_pt = x, y
            update()

    update()
    cv2.setMouseCallback('floodfill', onmouse)
    cv2.createTrackbar('lo', 'floodfill', 20, 255, update)
    cv2.createTrackbar('hi', 'floodfill', 20, 255, update)

    while True:
54
        ch = 0xFF & cv2.waitKey()
55 56 57 58 59 60 61 62 63 64
        if ch == 27:
            break
        if ch == ord('f'):
            fixed_range = not fixed_range
            print 'using %s range' % ('floating', 'fixed')[fixed_range]
            update()
        if ch == ord('c'):
            connectivity = 12-connectivity
            print 'connectivity =', connectivity
            update()
65
    cv2.destroyAllWindows()