Opencv_Python_5_ROI与泛洪填充

水漫(泛洪)填充算法实现
help(cv2.floodFill)

floodFill(image, mask, seedPoint, newVal[, loDiff[, upDiff[, flags]]]) -> retval, image, mask, rect
参数解释:
image:
mask:掩码图像,大小比原图多两个像素点。设输入图像大小为width * height, 则掩码的大小必须为 (width+2) * (height+2) , mask可为输出,也可作为输入 ,由flags决定。

seedPoint :填充标记点,去该点的像素值
newVal:填充值
loDiff:为像素值的下限差值
upDiff:为像素值的上限差值
flags参数 :
当为CV_FLOODFILL_FIXED_RANGE 时,待处理的像素点与种子点作比较,如果满足(s – lodiff , s + updiff)之间(s为种子点像素值),则填充;
当为CV_FLOODFILL_MASK_ONLY 时,则mask不能为空,此时,函数不填充原始图像img,而是填充掩码图像.

import cv2 as cv
import numpy as np


def fill_color_demo(image):    # 泛洪填充,flags为cv.FLOODFILL_FIXED_RANGE
    copy_img = image.copy()
    h, w = image.shape[0:2]
    mask = np.zeros([h+2, w+2], dtype=np.uint8)
    cv.floodFill(image=copy_img, mask=mask, seedPoint=(30, 30), newVal=(0, 255, 255),
                 loDiff=(100, 100, 100), upDiff=(50, 50, 50), flags=cv.FLOODFILL_FIXED_RANGE)
    cv.imshow("fill_color_demo", copy_img)


def fill_binary_demo(image):    # 二值图像填充,flags为cv.FLOODFILL_MASK_ONLY
    image = np.zeros([400, 400, 3], dtype=np.uint8)   # 用np.zeros()创建图
    image[100:300, 100:300, :] = 255
    cv.imshow("fill_binary", image)

    mask = np.ones([402, 402, 1], dtype=np.uint8)
    mask[101:301, 101:301] = 0
    cv.floodFill(image, mask, (200, 200), (0, 0, 255), cv.FLOODFILL_MASK_ONLY)
    cv.imshow("filled binary", image)


print("......hello world ! ......")
src = cv.imread("images/image1.jpg")
print(src.shape)
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
fill_color_demo(src)
fill_binary_demo(src)
cv.waitKey(0)

cv.destroyAllWindows()

你可能感兴趣的:(python_opencv)