分水岭算法分割图像python代码
时间: 2023-08-12 11:09:40 浏览: 124
以下是使用OpenCV实现图像分水岭算法的Python代码:
```python
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
# 读取图像
image = cv.imread("bi.jpg")
# 将图像转换为灰度图
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
# 将图像转换为RGB格式
imagergb = cv.cvtColor(image, cv.COLOR_BGR2RGB)
# 对灰度图进行阈值处理
ret1, thresh = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV + cv.THRESH_OTSU)
# 定义一个3x3的卷积核
kernel = np.ones((3, 3), np.uint8)
# 对二值图像进行形态学开运算
opening = cv.morphologyEx(thresh, cv.MORPH_OPEN, kernel, iterations=2)
# 对开运算后的图像进行膨胀操作
sure_bg = cv.dilate(opening, kernel, iterations=3)
# 计算距离变换图像
dist_transform = cv.distanceTransform(opening, cv.DIST_L2, 5)
# 根据距离变换图像确定前景区域
ret2, sure_fg = cv.threshold(dist_transform, 0.005*dist_transform.max(), 255, 0)
sure_fg = np.uint8(sure_fg)
# 确定未知区域
unknown = cv.subtract(sure_bg, sure_fg)
# 对前景区域进行连通组件标记
ret3, markers = cv.connectedComponents(sure_fg)
# 应用分水岭算法进行图像分割
img = cv.watershed(image, markers)
# 显示原始图像和分割结果
plt.subplot(121)
plt.imshow(imagergb)
plt.axis('off')
plt.subplot(122)
plt.imshow(img)
plt.axis('off')
plt.show()
cv.waitKey()
cv.destroyAllWindows()
```
请注意,这只是一个示例代码,你需要根据自己的需求和图像进行适当的调整。
#### 引用[.reference_title]
- *1* [分水岭算法图像分割(OpenCV+Python)](https://blog.csdn.net/weixin_39585761/article/details/110734821)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* *3* [python+opencv-13 分水岭算法实现图像分割](https://blog.csdn.net/bubid/article/details/108303527)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文