本文主要是介绍python实现opencv学习二十二:分水岭分割算法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
分水岭分割流程:图像->灰度->二值->距离变换->寻找种子->生成Marker->分水岭变换->输出
具体代码如下:
# -*- coding=GBK -*-
import cv2 as cv
import numpy as np# 分水岭算法
def water_image():print(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)# 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("形态操作", sure_bg)# distance transformdist = cv.distanceTransform(mb, cv.DIST_L2, 3)dist_output = cv.normalize(dist, 0, 1.0, cv.NORM_MINMAX)cv.imshow("距离变换", dist_output*70)ret, surface = cv.threshold(dist, dist.max()*0.6, 255, cv.THRESH_BINARY)cv.imshow("寻找种子", surface)surface_fg = np.uint8(surface)unknown = cv.subtract(sure_bg, surface_fg)ret, markers = cv.connectedComponents(surface_fg)print(ret)# watershed transfrommarkers += 1markers[unknown == 255] = 0markers = cv.watershed(src, markers=markers)src[markers == -1] = [0, 0, 255]cv.imshow("分水岭结果", src)src = cv.imread("C://02.png")
cv.imshow("原来", src)
water_image()
cv.waitKey(0)
cv.destroyAllWindows()
运行结果如下:
这篇关于python实现opencv学习二十二:分水岭分割算法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!