MATLAB: Automatic calculation of length of object in a binary image

image processing

I have the following binary image:
I manually select the start and end points using the ruler in imtool to get the length. Is there a way to automatically get the length i.e the first white pixel to last white pixel (longest length) without doing it manually.

Best Answer

The most robust way would be to call bwboundaries and run through the coordinates finding which two are farthest from each other. Using MajorAxisLength in regionprops() won't be as accurate as that since it fits the blob to an ellipse.
boundaries = bwboundaries(binaryImage);
x = boundaries(:, 1);
y = boundaries(:, 2);
maxDistance = -inf;
for index1 = 1 : length(x)
for index2 = 1 : length(y)
deltaX = x(index1) - x(index2);
deltaY = y(index1) - y(index2);
distance = sqrt(deltaX^2+deltaY^2);
if distance > maxDistance
and so on. I trust you know how to finish it.
Related Question