使用cv2代码,用分水岭分割的方法,对图片blob_original.tif进行处理,并显示出来
时间: 2024-03-14 13:43:13 浏览: 158
好的,以下是使用分水岭算法对图片进行分割并显示的 Python 代码:
```python
import cv2
import numpy as np
# 读取原始图片
img = cv2.imread('blob_original.tif')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化处理
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
# 消除噪声
kernel = np.ones((3, 3), np.uint8)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
# 膨胀操作,使得背景区域扩张
sure_bg = cv2.dilate(opening, kernel, iterations=3)
# 距离变换
dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
ret, sure_fg = cv2.threshold(dist_transform, 0.7*dist_transform.max(), 255, 0)
# 找到未知区域
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg, sure_fg)
# 标记连通区域
ret, markers = cv2.connectedComponents(sure_fg)
# 增加标记值,使得背景区域为1,未知区域为0
markers = markers + 1
markers[unknown == 255] = 0
# 分水岭算法
markers = cv2.watershed(img, markers)
img[markers == -1] = [255,0,0]
# 显示分割结果
cv2.imshow('segmented', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
运行以上代码,即可看到分割后的结果。
阅读全文