MATLAB: Regionprops returning “wrong” axis lengths

image analysisimage processingMATLAB

I have a segmentation pipeline which produces a binary mask fitted to the outline of a cell. When I use regionprops to measure the mask, it gives the Major and Minor axis lengths to be ~25% larger than they appear. Below is a minimum working example, and attached is an example mask
props = regionprops(mask,'MajorAxisLength','MinorAxisLength','Centroid','Orientation');
theta = 0:0.01:2*pi;
figure(1)
imagesc(mask)
hold on, axis image off
% Draw the ellipse on - for an ellipse with centre (x0, y0), semi-axis
% lengths (a,b), oriented at an angle phi above horizontal, the cartesian
% equations from the polar coordinates are as follows:
% x = a cos(theta) cos(phi) - b sin(theta) sin(phi) + x0
% y = a cos(theta) sin(phi) + b sin(theta) cos(phi) + y0
% Which is translated into indexed variables below
plot(0.5 * props.MajorAxisLength .* cos(theta) .* cos(props.Orientation) ...
- 0.5 * props.MinorAxisLength .* sin(theta) .* sin(props.Orientation)...
+ props.Centroid(1),... % x values end here
0.5 * props.MajorAxisLength .* cos(theta) .* sin(props.Orientation) ...
+ 0.5 * props.MinorAxisLength .* sin(theta) .* cos(props.Orientation)...
+ props.Centroid(2),'k--','LineWidth',2)
plot(props.Centroid(1),props.Centroid(2),'kx')
Here is the mask, with the measured ellipse drawn on.

Best Answer

That's because all the ellipse properties are not designed for hollow shapes. Matlab is trying to fit an ellipse just to the 'on' pixels of your shape (so it's trying to fit an ellipse to the walls of the pipe only) and failing. You can tell because the 'Circularity' is only about 0.2. It should be near one for something close to a circle.
The fix is to fill your shape before calling regionprops:
props = regionprops(imfill(mask, 'holes'), 'all');
With that the rest of your code works fine. 'Circularity' is now 0.96.
Related Question