opencv/samples/python/floodfill.py

81 lines
2.0 KiB
Python
Raw Normal View History

2013-03-06 14:41:02 +08:00
#!/usr/bin/env python
2012-10-17 07:18:30 +08:00
'''
Floodfill sample.
Usage:
floodfill.py [<image>]
Click on the image to set seed point
Keys:
f - toggle floating range
c - toggle 4/8 connectivity
ESC - exit
'''
# Python 2/3 compatibility
from __future__ import print_function
2012-10-17 07:18:30 +08:00
import numpy as np
import cv2 as cv
2012-10-17 07:18:30 +08:00
if __name__ == '__main__':
import sys
2013-03-06 14:41:02 +08:00
try:
fn = sys.argv[1]
except:
2018-11-14 23:56:21 +08:00
fn = 'fruits.jpg'
print(__doc__)
2012-10-17 07:18:30 +08:00
2018-11-14 23:56:21 +08:00
img = cv.imread(cv.samples.findFile(fn))
2013-03-06 14:41:02 +08:00
if img is None:
print('Failed to load image file:', fn)
2013-03-06 14:41:02 +08:00
sys.exit(1)
2012-10-17 07:18:30 +08:00
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:
cv.imshow('floodfill', img)
2012-10-17 07:18:30 +08:00
return
flooded = img.copy()
mask[:] = 0
lo = cv.getTrackbarPos('lo', 'floodfill')
hi = cv.getTrackbarPos('hi', 'floodfill')
2012-10-17 07:18:30 +08:00
flags = connectivity
if fixed_range:
flags |= cv.FLOODFILL_FIXED_RANGE
cv.floodFill(flooded, mask, seed_pt, (255, 255, 255), (lo,)*3, (hi,)*3, flags)
cv.circle(flooded, seed_pt, 2, (0, 0, 255), -1)
cv.imshow('floodfill', flooded)
2012-10-17 07:18:30 +08:00
def onmouse(event, x, y, flags, param):
global seed_pt
if flags & cv.EVENT_FLAG_LBUTTON:
2012-10-17 07:18:30 +08:00
seed_pt = x, y
update()
update()
cv.setMouseCallback('floodfill', onmouse)
cv.createTrackbar('lo', 'floodfill', 20, 255, update)
cv.createTrackbar('hi', 'floodfill', 20, 255, update)
2012-10-17 07:18:30 +08:00
while True:
ch = cv.waitKey()
2012-10-17 07:18:30 +08:00
if ch == 27:
break
if ch == ord('f'):
fixed_range = not fixed_range
print('using %s range' % ('floating', 'fixed')[fixed_range])
2012-10-17 07:18:30 +08:00
update()
if ch == ord('c'):
connectivity = 12-connectivity
print('connectivity =', connectivity)
2012-10-17 07:18:30 +08:00
update()
cv.destroyAllWindows()