# How to find weighted centroid of an entire image in MATLAB

99 views (last 30 days)
Cameron Park on 27 Jul 2017
Answered: Image Analyst on 31 Jul 2017
I am trying to find the weighted centroid of the following image (attached). After lookng through similar posted questions I have tried the following:
%%option 1
A=I;
C=cellfun(@(n) 1:n, num2cell(size(A)),'uniformoutput',0);
[C{:}]=ndgrid(C{:});
C=cellfun(@(x) x(:), C,'uniformoutput',0);
C=[C{:}];
CenterOfMass=A(:).*C/sum(A(:),'double');
%option2
grayImage=I;
binaryImage = true(size(grayImage));
labeledImage = bwlabel(binaryImage);
measurements = regionprops(labeledImage, grayImage, 'WeightedCentroid');
centerOfMass = measurements.WeightedCentroid;
neither method worked and came up with error messages. I tried playing with the regionprops function but don't think that is working. I was thinking I could create a forloop that loops through the entire image weighting each pixel's location and intensity to get the center of the whole region. Not sure if this would work or how to properly execute. Does anyone know how to do this or know of a better way? Thank you! All help welcome!

Image Analyst on 31 Jul 2017
Option 2 works just fine. Not sure what you're talking about.
binaryImage = true(size(grayImage));
labeledImage = bwlabel(binaryImage);
measurements = regionprops(labeledImage, grayImage, 'WeightedCentroid')
centerOfMass = measurements.WeightedCentroid
hold on;
plot(centerOfMass(1), centerOfMass(2), 'r*', 'LineWidth', 2, 'MarkerSize', 16);
No error messages whatsoever. Please explain.
Also, regionprops() returns a structure (as in your case of a single blob), or an array of structures (in the case of multiple blobs). If does not create a for loop. Everything (like computing centroids or other measurements) is done internally by regionprops().

Shruti Shivaramakrishnan on 31 Jul 2017
Consider the following code snippet from the example: https://www.mathworks.com/help/images/examples/measuring-regions-in-grayscale-images.html
s = regionprops(BW, I, {'Centroid','WeightedCentroid'}); To compare the weighted centroid locations with the unweighted centroid locations, display the original image and then, using the hold and plot functions, superimpose the centroids on the image.
imshow(I) title('Weighted (red) and Unweighted (blue) Centroids'); hold on numObj = numel(s); for k = 1 : numObj plot(s(k).WeightedCentroid(1), s(k).WeightedCentroid(2), 'r*'); plot(s(k).Centroid(1), s(k).Centroid(2), 'bo'); end hold off
The following blog post might be interesting as well: https://blogs.mathworks.com/steve/2007/08/31/intensity-weighted-centroids/