How to calculate width of each worm in the image?

Code

_, binary = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV)

#find the contours from the thresholded image
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2:]

#Calculate Maximum Width of each worms using Distance Transform

distance = cv2.distanceTransform(binary, cv2.DIST_L2,5)
print('gray',binary.shape)
minv,maxv,minp,maxp = cv2.minMaxLoc(distance)
print(distance)
print(maxv*2, maxp)# (half)width*2, pos
print('Min',minv*2,minp)
draw = cv2.cvtColor(binary, cv2.COLOR_GRAY2BGR)
cv2.line(draw, (0,maxp[1]), (binary.shape[1],maxp[1]), (250,0,0),2, -1)
cv2.line(draw, (0,minp[1]), (binary.shape[1],minp[1]), (250,0,0),2, -1)
plt.figure(figsize=(15, 15))
plt.imshow(draw)
plt.show()

Maximum distance: 17.575199127197266 (1144, 787)

Minimum distance: 0.0 (0, 0)

Output Image

related

1 Like

your own code should have answered your question. do you agree?

1 Like

Hi @crackwitz , I did not get accurate cross section width and I need width of each worms.

You can use thinining algorithm in opencv_contrib same problem here

1 Like

Thanks @laurent.berger for your solution, I have solved this problem with my own code. I am thinking of optimized approach and will try your too.

can you tell what does this maximum distance 17.575199… represents, i mean is it in pixels or what? I want to report maximum width of surface crack using similar algorithm but what will this value obtained signify.