My understanding is the second central moment should give me an object's variance. Which I should be able to use as a measure of distribution of pixels from the center of the object, and so I would think I could find the size of the enclosing rectangle of an object using the second moments. Say in Malab I create an image with a white rectangle of dimensions 100x200 and find the center of mass using the first moments, then I calculate the variance
im = zeros(501,400);
im(200:300,100:300) = ones(101,201);
%Sum the moments in a for loop for clarity
for v = 1:rows
for u = 1:cols
val = im(v,u);
%zeroth moment is just the total pixel count
m00 = m00 + val;
%First moments. pixel value times position is the m10 and m01
m01 = m01 + (val * v);
m10 = m10 + (val * u);
end
end
%centers of mass
uc = m10/m00;
vc = m01/m00;
%Now I find the second central moments wrt centroid
for v = 1:rows
for u = 1:cols
val = im(v,u);
u02 = u02 + (v - vc)^2 * val;
u20 = u20 + (u - uc)^2 * val;
end
end
hold on;
plot(uc,vc, 'r+');
text(uc + 5,vc + 5,strcat('X:',num2str(uc)),'Color','green','FontSize',12);
text(uc + 5,vc + 20,strcat('Y:',num2str(vc)),'Color','green','FontSize',12);
My value for u02 is 17255850, the square root of which is 4154. Is there a way I can directly get the approximate size of my rectangle using the variance? Thanks for any help.
EDIT: Experimenting with fitting an ellipse using the covariance matrix and trying to calculate the size using the variance as discussed in the comments and I get the image below. The dimensions of the yellow rectangle were calculated with
%can we estimate size based on standard deviation?
stdX = sqrt(u20/m00);
stdY = sqrt(u02/m00);
rectangle('Position',[uc-2*stdX vc-2*stdY 4*stdX 4*stdY],'EdgeColor','yellow');