分水岭算法
import cv2 as cv
import numpy
def watershed_demo():
# remove noise if any 消除噪声
print(src.shape)
# gray, binary image
blurred = cv.pyrMeanShiftFiltering(src, 10, 100)
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))
# morphology binary,2次开操作
mb = cv.morphologyEx(binary, cv.MORPH_OPEN, kernel, iterations=2)
sure_bg = cv.dilate(mb, kernel, iterations=3) # 3次膨胀
cv.imshow("mor-opt", sure_bg)
# distance transform
# distance transform
# DIST_L1:曼哈顿距离,DIST_L2:欧氏距离, masksize:跟卷积一样
# 这是我们获取的字段距离数值,对应每个像素都有,所以数组结构和图像数组一致
dist = cv.distanceTransform(mb, cv.DIST_L2, 3)
dist_output = cv.normalize(dist, 0, 1.0, cv.NORM_MINMAX) # 归一化的距离图像数组 0-1之间标准化
# cv.imshow("distance-t", dist_output*50) # 这行代码运行不了
ret, surface = cv.threshold(dist, dist.max()*0.5, 255, cv.THRESH_BINARY)
# cv.imshow("surface_bin", surface) # 个人运行不了
# 计算marker
surface_fg = numpy.uint8(surface) # 计算前景
unknown = cv.subtract(sure_bg, surface_fg) # 计算未知区域
ret, markers = cv.connectedComponents(surface_fg)
print(ret)
# watershed transform 分水岭变换
markers = markers + 1 # 用label进行控制
markers[unknown == 255] = 0
markers = cv.watershed(src, markers=markers) # 分水岭的地方就编程-1
src[markers == -1] = [0, 0, 255]
cv.imshow("result_image", src)
src = cv.imread("./data/coins.png", cv.IMREAD_COLOR)
cv.namedWindow("girl", cv.WINDOW_AUTOSIZE)
cv.imshow("girl", src)
watershed_demo()
cv.waitKey(0)
cv.destroyAllWindows()
运行结果