#导包:cv2视觉、numpy数组
import cv2
import numpy as np
#加载图片
img =cv2.imread('mourse.jpg')
cv2.imshow('ori',img)
#转换图片为黑白色
gray =cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#将图片阈值分割
ret,thresh =cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
cv2.imshow('thresh',thresh)
#腐蚀图片
kernel =np.ones((3,3),np.uint8)
opening =cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel,iterations=2)
cv2.imshow('opening',opening)
closing =cv2.morphologyEx(opening,cv2.MORPH_CLOSE,kernel,iterations=20)
cv2.imshow('closing',closing)
#膨胀图片
sure_bg =cv2.dilate(closing,kernel,iterations=3)
cv2.imshow('sure_bg',sure_bg)
#图像分割
dist_transform =cv2.distanceTransform(closing,1,5)
ret,sure_fg =cv2.threshold(dist_transform,0.3 * dist_transform.max(),255,0)
cv2.imshow('sure_fg',sure_fg)
#转换数据类型
sure_fg =np.uint8(sure_fg)
unknown =cv2.subtract(sure_bg,sure_fg)
cv2.imshow('unknown',unknown)
ret,markresl =cv2.connectedComponents(sure_fg)
maekers =markresl+1
maekers[unknown ==255] =0
markers3 =cv2.watershed(img,maekers)
img[markers3 == -1] =[0,255,0]
cv2.imshow('img',img)
cv2.waitKey(0)
标签:sure,img,fg,imshow,cv2,算法,图像,closing,分水岭
From: https://www.cnblogs.com/luzhangan/p/18499986