使用 openCV 计算树突中的突起 (python)

Count protuberances in dendrite with openCV (python)

我正在尝试使用 Python 和 OpenCV 计算通过荧光显微镜获得的小鼠树突中的树突棘(微小的突起)。

这是我开始的原始图片:

原始图片:

经过一些预处理(下面的代码)我得到了这些轮廓:

带轮廓的原始图片(白色):

我需要做的是识别所有的突起,得到这样的东西:

带有白色轮廓和红色预期计数的原始图片:

我打算做的是,在对图像进行预处理(二值化、阈值化和降低噪声)之后,绘制轮廓并尝试在其中找到凸缺陷。问题出现了,因为一些 "spines"(这些突起的技术名称)没有被识别,因为它们在同一个凸缺陷中一起凸出,低估了结果。有没有什么办法可以在标记凸性缺陷的时候多"precise"

轮廓为白色的原始图像。红点标记了用我的代码标识的脊椎。绿点标记我仍然无法识别的刺:

我的Python代码:

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

#Image loading and preprocessing:

img = cv2.imread('Prueba.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = cv2.pyrMeanShiftFiltering(img,5,11)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret,thresh1 = cv2.threshold(gray,5,255,0)

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
img1 = cv2.morphologyEx(thresh1, cv2.MORPH_OPEN, kernel)
img1 = cv2.morphologyEx(img1, cv2.MORPH_OPEN, kernel)
img1 = cv2.dilate(img1,kernel,iterations = 5)

#Drawing of contours. Some spines were dettached of the main shaft due to
#image bad quality. The main idea of the code below is to identify the shaft
#as the biggest contour, and count any smaller as a spine too.

_, contours,_ = cv2.findContours(img1,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
print("Number of contours detected: "+str(len(contours)))

cv2.drawContours(img,contours,-1,(255,255,255),6)
plt.imshow(img)
plt.show()

lengths = [len(i) for i in contours]
cnt = lengths.index(max(lengths))

#The contour of the main shaft is stored in cnt    

cnt = contours.pop(cnt)

#Finding convexity points with hull:

hull = cv2.convexHull(cnt) 

#The next lines are just for visualization. All centroids of smaller contours
#are marked as spines.

for i in contours:

    M = cv2.moments(i)
    centroid_x = int(M['m10']/M['m00'])
    centroid_y = int(M['m01']/M['m00'])
    centroid = np.array([[[centroid_x, centroid_y]]])

    print(centroid)

    cv2.drawContours(img,centroid,-1,(0,255,0),25)
    cv2.drawContours(img,centroid,-1,(255,0,0),10)

cv2.drawContours(img,hull,-1,(0,255,0),25)
cv2.drawContours(img,hull,-1,(255,0,0),10)

plt.imshow(img)
plt.show()

#Finally, the number of spines is computed as the sum between smaller contours
#and protuberances in the main shaft.

spines = len(contours)+len(hull)
print("Number of identified spines: " + str(spines))

我知道我的代码还有许多小问题需要解决,但我认为最大的问题是此处介绍的问题。

感谢您的帮助!并且有一个好的

我会按照 Silencer 的建议将轮廓近似为多边形(不要使用凸包)。也许你应该稍微简化轮廓以保留形状的大部分细节。

这样,您将有许多必须过滤的顶点:查看每个顶点的角度,您可以判断它是凹的还是凸的。每个脊椎是一个或多个凹顶点之间的凸顶点(如果你有几个连续的凸顶点,你只保留较尖的一个)。

编辑:为了计算角度,您可以执行以下操作:假设 a、b 和 c 是三个连续的顶点

angle1 = arctan((by-ay)/(bx-ax))
angle2 = arctan((cy-by)/(cx-bx))
angleDiff=angle2-angle1
if(angleDiff<-PI) angleDiff=angleDiff+2PI

if(angleDiff>0) concave
Else convex

反之亦然,这取决于你的轮廓是顺时针还是逆时针,黑色还是白色。如果对任何多边形的所有 angleDiff 求和,结果应该是 2PI。如果是-2PI,那么最后一个"if"应该换掉。