立即学习:https://edu.csdn.net/course/play/26281/327090?utm_source=blogtoedu
import numpy as np
import cv2
import copy
filename = r'C:\Users\c\Pictures\fruits.jpg'
img=cv2.imread(filename)
if img is None:
print('Failed to load image file')
sys.exit(1)
h,w=img.shape[:2]
mask=np.zeros((h+2,w+2),np.uint8)
seed_pt=None
fixed_range=True
connectivity=4 #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
if flags & cv2.EVENT_FLAG_LBUTTON:
seed_pt=x,y
update()
update()#显示初始图片
cv2.setMouseCallback('floodfill',onmouse)#关联鼠标左键与要执行的函数
cv2.createTrackbar('lo','floodfill',20,255,update)#创建控制条
cv2.createTrackbar('hi','floodfill',20,255,update)
ch=cv2.waitKey()
if ch==27: #ESC键退出
cv2.destroyAllWindows()