分水岭分割流程:图像->灰度->二值->距离变换->寻找种子->生成Marker->分水岭变换->输出
参考:
python OpenCV学习笔记(二十九):图像流域(分水岭)分割算法
import cv2 as cv
import numpy as np
def watershed_demo():
print(src.shape)
# 模糊操作
blur = cv.pyrMeanShiftFiltering(src, 10, 100)
# 灰度、二值化图像
gray = cv.cvtColor(blur, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
cv.imshow("binary", binary)
# morphology operation
kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))
mb = cv.morphologyEx(binary, cv.MORPH_OPEN, kernel, iterations=2)
sure_bg = cv.morphologyEx(mb, cv.MORPH_CLOSE, kernel, iterations=3)
cv.imshow("morphology operation", sure_bg)
# distance transform
dist = cv.distanceTransform(mb, cv.DIST_L2, 3)
dist_output = cv.normalize(dist, 0, 1, cv.NORM_MINMAX)
cv.imshow("distance_t", dist_output*50)
ret, surface = cv.threshold(dist, dist.max()*0.6, 255, cv.THRESH_BINARY)
cv.imshow("surface", surface)
surface_fg = np.uint8(surface)
unknown = cv.subtract(sure_bg, surface_fg)
ret, markers = cv.connectedComponents(surface_fg)
print("ret =", ret)
# 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)
print("--------- Hello Python ---------")
src = cv.imread("D:/opencv/coins1.jpg")
# cv.namedWindow("coins", cv.WINDOW_AUTOSIZE)
# cv.imshow("coins", src)
watershed_demo()
cv.waitKey(0)
cv.destroyAllWindows()