写python代码进行图像中细胞的分析处理,显示每次处理后的图像,要求进行图像分割,将图像中细胞分割为两类或三类,细胞计数,重叠或粘连的细胞要计数成多个;不完整的细胞记成一个;最后分别对细胞进行记数
时间: 2023-09-11 18:08:26 浏览: 278
好的,感谢您的要求,下面是一份基于Python OpenCV库的细胞分析处理代码,按照您的需求进行了修改:
```python
import cv2
import numpy as np
# 定义颜色范围,通过颜色阈值分割细胞
lower = np.array([0, 0, 0])
upper = np.array([255, 255, 255])
# 加载图像
img = cv2.imread("cell.jpg")
# 颜色阈值分割
mask = cv2.inRange(img, lower, upper)
# 去除噪点,使用开运算
kernel = np.ones((5, 5), np.uint8)
opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
# 寻找轮廓,计算细胞个数
contours, hierarchy = cv2.findContours(opening, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 分割细胞,将细胞按照大小分为两类或三类
cells = []
for i in range(len(contours)):
area = cv2.contourArea(contours[i])
if area < 500:
cells.append((contours[i], 0)) # 小细胞
elif area > 2000:
cells.append((contours[i], 2)) # 大细胞
else:
cells.append((contours[i], 1)) # 中等大小的细胞
# 绘制分割后的细胞
cell_img = np.zeros_like(img)
for i in range(len(cells)):
if cells[i][1] == 0:
color = (255, 0, 0)
elif cells[i][1] == 1:
color = (0, 255, 0)
else:
color = (0, 0, 255)
cv2.drawContours(cell_img, [cells[i][0]], -1, color, 2)
# 计算细胞个数
num_small_cells = 0
num_medium_cells = 0
num_large_cells = 0
for i in range(len(cells)):
area = cv2.contourArea(cells[i][0])
if area < 500:
num_small_cells += 1
elif area > 2000:
num_large_cells += 1
else:
num_medium_cells += 1
# 将重叠或粘连的细胞计数成多个
num_overlapping_cells = 0
for i in range(len(cells)):
for j in range(i+1, len(cells)):
if cv2.contourArea(cv2.convexHull(cells[i][0])) > cv2.contourArea(cells[j][0]):
if cv2.pointPolygonTest(cells[i][0], tuple(cells[j][0][0][0]), False) == 1:
num_overlapping_cells += 1
else:
if cv2.pointPolygonTest(cells[j][0], tuple(cells[i][0][0][0]), False) == 1:
num_overlapping_cells += 1
# 计算不完整的细胞个数
num_incomplete_cells = 0
for i in range(len(cells)):
perimeter = cv2.arcLength(cells[i][0], True)
if perimeter < 200:
num_incomplete_cells += 1
# 打印细胞个数
print(f"Number of small cells: {num_small_cells}")
print(f"Number of medium cells: {num_medium_cells}")
print(f"Number of large cells: {num_large_cells}")
print(f"Number of overlapping cells: {num_overlapping_cells}")
print(f"Number of incomplete cells: {num_incomplete_cells}")
# 显示细胞分割结果
cv2.imshow("Cell Segmentation", cell_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
上述代码在原有细胞分割的基础上,增加了对不同类型细胞的计数,重叠或粘连的细胞计数成多个,不完整的细胞计数成一个。具体来说,我们通过计算细胞的面积将细胞按照大小分为两类或三类,然后遍历所有细胞,判断是否与其他细胞重叠或粘连,同时计算不完整细胞的个数。最后,打印出不同类型细胞的个数并显示细胞分割结果。
同样地,您可以根据需求对代码进行修改和完善,例如调整颜色阈值、修改细胞大小分类的阈值、改变绘制细胞的颜色等。
阅读全文