Dendrite graph calculations using openCV (python)

I am trying to count dendritic spikes (tiny protrusions) in mouse dendrites obtained by fluorescence microscopy using Python and OpenCV.

Here is the source image I'm starting from:

Original Image:

enter image description here

After some preprocessing (code below) I got these outlines:

Raw image with outlines (white):

enter image description here

What I need to do is recognize all the protrusions by getting something like this:

Raw image with outlines in white and expected quantity in red:

enter image description here

, , (, ), . , "" ( ) , , . "" ?

, . , . , :

enter image description here

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))

, , , .

!

+4
1

, Silencer ( ). , , .

, , : , , . ( , ).

EDIT: : , 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" .

+2

Source: https://habr.com/ru/post/1692603/


All Articles