分水岭算法

  • 距离变换
import cv2 as cv
import numpy as np


def watershed_demo():
    """ 前期的处理需要做好 :return: """
    # remove noise if any
    print(src.shape)
    blurred = cv.pyrMeanShiftFiltering(src, 10, 100)
    # gray\binary image
    # 灰度化
    gray = cv.cvtColor(blurred, cv.COLOR_BGR2GRAY)
    # 自动阈值 二值化
    ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
    cv.imshow("binary-image", binary)

    # morphology operation 形态学操作
    # 核
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))
    # 开操作 连续两次
    mb = cv.morphologyEx(binary, cv.MORPH_OPEN, kernel, iterations=2)
    # 膨胀操作
    sure_bg = cv.dilate(mb, kernel, iterations=3)
    cv.imshow("mor-opt", sure_bg)

    # distance transform 距离变换
    # 计算方式 掩膜大小
    dist = cv.distanceTransform(mb, cv.DIST_L1, 3)
    #
    dist_output = cv.normalize(dist, 0, 1.0, cv.NORM_MINMAX)
    cv.imshow("distance-t", dist_output * 50)

    ret, surface = cv.threshold(dist, dist.max() * 0.6, 255, cv.THRESH_BINARY)

    surface_fg = np.uint8(surface)
    cv.imshow("surface-bin", surface_fg)
    unknown = cv.subtract(sure_bg, surface_fg)
    # 求取连通区域
    ret, markers = cv.connectedComponents(surface_fg)
    print('ret= ',ret)
    print('markers 类型', type(markers))
    # watershed transform
    markers = markers + 1
    markers[unknown == 255] = 0
    # 分水岭
    markers = cv.watershed(src, markers=markers)
    src[markers == -1] = [0, 0, 255]
    cv.imshow("result", src)


src = cv.imread("main.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
watershed_demo()
cv.waitKey(0)

cv.destroyAllWindows()

这一部分没有很懂 后面再补上