用opencv结合层次分水岭和细胞计数并在图上标记细胞数字,写出具体代码
时间: 2024-03-23 08:39:48 浏览: 59
好的,以下是一个简单的用OpenCV实现细胞计数并标记的代码,主要使用了层次分水岭算法和形态学操作:
```python
import cv2
import numpy as np
# 读入图像并转为灰度图
img = cv2.imread('cells.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 高斯模糊去噪声
blur = cv2.GaussianBlur(gray, (5, 5), 0)
# Sobel算子求梯度
grad_x = cv2.Sobel(blur, cv2.CV_32F, 1, 0, ksize=3)
grad_y = cv2.Sobel(blur, cv2.CV_32F, 0, 1, ksize=3)
grad = cv2.subtract(grad_x, grad_y)
grad = cv2.convertScaleAbs(grad)
# 形态学操作,闭运算
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 9))
closed = cv2.morphologyEx(grad, cv2.MORPH_CLOSE, kernel)
# 膨胀操作,放大细胞
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (21, 21))
dilation = cv2.dilate(closed, kernel)
# 距离变换,寻找分水岭中的种子点
dist_transform = cv2.distanceTransform(dilation, cv2.DIST_L2, 5)
ret, sure_fg = cv2.threshold(dist_transform, 0.5 * dist_transform.max(), 255, 0)
sure_fg = np.uint8(sure_fg)
# 执行分水岭算法
unknown = cv2.subtract(sure_bg, sure_fg)
ret, markers = cv2.connectedComponents(sure_fg)
markers = markers + 1
markers[unknown == 255] = 0
markers = cv2.watershed(img, markers)
# 标记并显示细胞数量
cells_num = len(np.unique(markers)) - 1
cv2.putText(img, f'Cells: {cells_num}', (30, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
cv2.imshow('Result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
需要注意的是,以上代码只适用于特定的图像,可能需要根据实际情况进行调整。
阅读全文