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