image.png image.png image.png image.png应用于:图像分割
def watershed_function(image):
# 前提:降噪
blurred = cv.pyrMeanShiftFiltering(image, 25, 100)
# 第一步:灰度处理
gray = cv.cvtColor(blurred, cv.COLOR_BGR2GRAY)
# 第二步:二值化处理
ret, binary = cv.threshold(
gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
cv.imshow("binary", binary)
# 第三步:距离变换
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("open then dilate", sure_bg)
'''
distance_TYpe = cv.DIST_L2:欧几何距离
maskSize = 3
'''
distance = cv.distanceTransform(mb, cv.DIST_L2, 3)
dist_output = cv.normalize(distance, 0, 1.0, cv.NORM_MINMAX)
cv.imshow("distance", dist_output*50)
# 第四步:寻找种子
ret, surface = cv.threshold(distance, distance.max()*0.6, 255, cv.THRESH_BINARY)
cv.imshow("surface", surface)
# 第五步:生成marker
surface_fg = np.uint8(surface) #将 float 转为8位
unknown = cv.subtract(sure_bg, surface_fg)
ret, markers = cv.connectedComponents(surface_fg) #连通区域
print(ret)
# 分水岭变换
markers = markers + 1
markers[unknown == 255] = 0
markers = cv.watershed(image, markers=markers)
image[markers == -1] = [0, 0, 255] #分水岭标记为红色
cv.imshow("分水岭", image)
红色标记分水岭
网友评论