Python+OpenCV:基于分水岭算法的图像分割(Image Segmentation with Watershed Algorithm)
####################################################################################################
# 基于分水岭算法的图像分割(Image Segmentation with Watershed Algorithm)
def lmc_cv_image_segmentation_watershed():
"""
函数功能: 基于分水岭算法的图像分割(Image Segmentation with Watershed Algorithm)。
"""
# 读取图像
image = lmc_cv.imread('D:/99-Research/Python/Image/water_coins.jpg', flags=lmc_cv.IMREAD_UNCHANGED)
rgb_image = lmc_cv.cvtColor(image, lmc_cv.COLOR_BGR2RGB)
rgb_image_result = rgb_image.copy()
gray_image = lmc_cv.cvtColor(rgb_image, lmc_cv.COLOR_RGB2GRAY)
# 基于分水岭算法的图像分割(Image Segmentation with Watershed Algorithm)
ret, thresh_image = lmc_cv.threshold(gray_image, 0, 255, lmc_cv.THRESH_BINARY_INV + lmc_cv.THRESH_OTSU)
# noise removal
kernel = np.ones((3, 3), np.uint8)
opening_image = lmc_cv.morphologyEx(thresh_image, lmc_cv.MORPH_OPEN, kernel, iterations=2)
# sure background area
sure_bg_image = lmc_cv.dilate(opening_image, kernel, iterations=3)
# Finding sure foreground area
dist_transform = lmc_cv.distanceTransform(opening_image, lmc_cv.DIST_L2, 5)
ret, sure_fg_image = lmc_cv.threshold(dist_transform, 0.7 * dist_transform.max(), 255, 0)
# Finding unknown region
sure_fg_image = np.uint8(sure_fg_image)
unknown = lmc_cv.subtract(sure_bg_image, sure_fg_image)
# Marker labelling
ret, markers_image = lmc_cv.connectedComponents(sure_fg_image)
# Add one to all labels so that sure background is not 0, but 1
markers_image = markers_image + 1
# Now, mark the region of unknown with zero
markers_image[unknown == 255] = 0
markers_image = lmc_cv.watershed(rgb_image_result, markers_image)
rgb_image_result[markers_image == -1] = [255, 0, 0]
# 显示图像
pyplot.figure('Image Display')
titles = ['Original Image', 'Thresh Image', 'ForeGround Image', 'BackGround Image', 'Distance Transform Image',
'Markers Image', 'Result Image']
images = [rgb_image, thresh_image, sure_fg_image, sure_bg_image, dist_transform, markers_image, rgb_image_result]
for i in range(7):
pyplot.subplot(2, 4, i + 1)
pyplot.imshow(images[i], 'gray')
pyplot.title(titles[i])
pyplot.xticks([])
pyplot.yticks([])
pyplot.show()
# 根据用户输入保存图像
if ord("q") == (lmc_cv.waitKey(0) & 0xFF):
# 销毁窗口
pyplot.close('all')
return

还没有评论,来说两句吧...