python opencv 分水岭算法对图像进行分割

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

img = cv2.imread('coin.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)

print(thresh.shape)
# cv2.imshow(thresh)
# cv2.waitKeyai(0)
# cv2.destroyAllWindows()
plt.imshow(thresh,'gray')
(312, 252)





<matplotlib.image.AxesImage at 0x2119d576438>

png

# noise removal
kernel = np.ones((3,3),np.uint8)
opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)

# sure background area
sure_bg = cv2.dilate(opening,kernel,iterations=3)

# Finding sure foreground area
dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,5)
ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0)
print(sure_fg.dtype)
# Finding unknown region
sure_fg = np.uint8(sure_fg)
print(sure_fg.dtype)
unknown = cv2.subtract(sure_bg,sure_fg)

plt.imshow(sure_fg,'gray')

float32
uint8





<matplotlib.image.AxesImage at 0x2119fc4e668>

png

# Marker labelling
ret, markers = cv2.connectedComponents(sure_fg)
print(markers.shape)
# 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
plt.imshow(sure_fg)


(312, 252)





<matplotlib.image.AxesImage at 0x2119fc95f98>

png

markers = cv2.watershed(img,markers)
img[markers == -1] = [255,0,0]

plt.imshow(img)
<matplotlib.image.AxesImage at 0x2119fd9b208>

png

plt.imshow(markers)
<matplotlib.image.AxesImage at 0x211a0dc4cf8>

png

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值