python + opencv图像处理——分水岭算法

基于距离的分水岭分割流程:

1、输入图像
2、灰度(消除噪声)
3、二值化
4、距离变换
5、寻找种子
6、生成Marker
7、分水岭变换
8、输出图像

from matplotlib import pyplot as plt 
from cv2 import cv2 as cv
import numpy as np 

def watearshel_demo():
    print(img.shape)
    blured = cv.pyrMeanShiftFiltering(img,10,80)
    #操作步骤  gray/binary image  
    gray = cv.cvtColor(blured,cv.COLOR_BGR2GRAY)#观察灰度处理后的图像好不好,不好就进行滤波
    ret,binary = cv.threshold(gray,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)
    cv.imshow("binary_image",binary)

    # morphology operation
    kernel = cv.getStructuringElement(cv.MORPH_RECT,(1,1))#结构元素
    mb = cv.morphologyEx(binary,cv.MORPH_OPEN,kernel,iterations=2)#进行2次开操作
    sure_bg = cv.dilate(mb,kernel,iterations=3)#进行3次膨胀
    cv.imshow("mor",sure_bg)

    #distace transform  
    #对mb进行距离变换
    dist = cv.distanceTransform(mb,cv.DIST_L2,3)
    dist_output = cv.normalize(dist,0,1.0,cv.NORM_MINMAX)
    cv.imshow("distanc_transform",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)#转成int
    unknow = cv.subtract(sure_bg,surface_fg)
    ret,markers = cv.connectedComponents(surface_fg)
    print(ret)

    # watershed transform
    markers = markers + 1
    markers[unknow == 255] = 0
    markers = cv.watershed(img,markers=markers)
    img[markers==-1] = [0,0,255]#红色
    cv.imshow('result',img)
    #cv.imwrite('C:\\pictures\\Test paper\\6.jpg',img)
    
if __name__ == "__main__":
    #filepath = "C:\\pictures\\Test paper\\unqualified\\2019_01_09__16_09_03_452_A.jpg"
    filepath = "C:\\pictures\\others\\measure2.jpg"
    img = cv.imread(filepath)       # blue green red
    cv.namedWindow("input image",cv.WINDOW_AUTOSIZE)
    cv.imshow("input image",img)

    watearshel_demo()

    cv.waitKey(0)
    cv.destroyAllWindows()

图片如下:
在这里插入图片描述

你可能感兴趣的:(opencv)