OpenCV教程:
https://docs.opencv.org/master/d3/db4/tutorial_py_watershed.html
图像二值化后,背景为黑,前景为白,用这个二值图像去做Distance Transform,就会得到距离矩阵,这个矩阵的尺寸和二值图像大小相同,而其中的每一个值代表的是该像素点到最近的黑色像素点的远近度,越远,值越高,距离矩阵中该点越亮。
我们再将距离矩阵二值化后,就得到了前景种子图像,图像中每一个白色区域必定处于原图的前景中,也因此每一个白色区域是一个种子,分水岭算法会用这些种子往图的四周注水,然后得到边缘。
最后直接用于cv.watershed()的图像有三部分:背景,前景种子,未知区域。其中未知区域是边缘所处的一小片区域,这片区域是用原图二值图经过膨胀后的图像减去前景种子图后得到的图像中的白色区域。
OpenCV教程源码:
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('C:/cvtest/water_coins.jpg')
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
cv.imshow("binary", thresh)
# noise removal
kernel = np.ones((3, 3), np.uint8)
opening = cv.morphologyEx(thresh, cv.MORPH_OPEN, kernel, iterations=2) # 开操作:先腐蚀后膨胀
cv.imshow("opening", opening)
# sure background area
sure_bg = cv.dilate(opening, kernel, iterations=3)
cv.imshow("sure background area", sure_bg)
# Finding sure foreground area
dist_transform = cv.distanceTransform(opening, cv.DIST_L2, 5)
cv.normalize(dist_transform, dist_transform, 0, 1.0, cv.NORM_MINMAX)
cv.imshow('Distance Transform Image', dist_transform) # ?这里不把dist_transform进行normalize的话显示的是和opening一样的图像,不懂
ret, sure_fg = cv.threshold(dist_transform, 0.7 * dist_transform.max(), 255, 0)
cv.imshow("sure foreground area", sure_fg)
# Finding unknown region
sure_fg = np.uint8(sure_fg)
unknown = cv.subtract(sure_bg, sure_fg)
cv.imshow("unknown region", unknown)
# Marker labelling
ret, markers = cv.connectedComponents(sure_fg.astype(np.uint8))
# Add one to all labels so that sure background is not 0, but 1
markers = markers + 1
# Now, mark the region of unknown with zero
markers[unknown == 255] = 0
# Now our marker is ready. It is time for final step, apply watershed.
# Then marker image will be modified. The boundary region will be marked with -1.
markers = cv.watershed(img, markers)
img[markers == -1] = [255, 0, 0]
cv.imshow("watershed", img)
cv.waitKey(0)