一、基本原理
分水岭算法主要是基于距离变换(distance transform),找到mark一些种子点,从这些种子点出发根据像素梯度变化进行寻找边缘并标记
分水岭:可以简单的理解成一座山,然后来洪水了,水开始上涨淹没山,慢慢的水位上升,一些海拔低的地方就被淹没。
二、基于距离的分水岭分割思路
开始—输入图像—转换为灰度图—消除噪声—转换为二值图像—距离变化—寻找种子—生产marker—分水岭变换—输出图像—结束
三、代码实现
import cv2 as cv
import numpy as npdef watershed():# remove noise if anyprint(src.shape)blurred = cv.pyrMeanShiftFiltering(src, 10, 100)#边缘保留滤波,消除噪声# gray\binary imagegray = 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 operationkernel = 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 transformdist = cv.distanceTransform(mb, cv.DIST_L2, 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)print(ret)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)# watershed transformmarkers = markers + 1markers[unknown==255] = 0markers = cv.watershed(src, markers=markers)src[markers==-1] = [0, 0, 255]cv.imshow("result", src)src = cv.imread(r"G:\Juptyer_workspace\study\opencv\opencv3/coins.jpg")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
watershed()
cv.waitKey(0)cv.destroyAllWindows()
效果图如下: