MATLAB Answers


Center of mass in binary image

Asked by Felix
on 18 Sep 2013

Hello, I have a binary image with one object. How can I calculate the center of this object, to mark it in my image and to write the coordinates in the corner of this image, like this: object: X, Y

I used this code to calculate the center of mass:

s = regionprops(bw, 'centroid');

centroids = cat(1, s.Centroid);


hold on

plot(centroids(:,1), centroids(:,2), 'b*')

hold off

but how can i plot this coordinates on my image in the left corner?

Thank you for help



No products are associated with this question.

2 Answers

Answer by David Sanchez
on 18 Sep 2013
 Accepted answer

use text command:

your_string = strcat( num2str(centroids(:,1)),'-', num2str(centroids(:,2)));

change the position by changing the "10,10" values


on 18 Sep 2013

Thank you it's works, another question, how can i write in this way:

Object: X,Y(coordinates)

now it gives me only a coordinates and can i also write a coordinates without a numbers after '.'? only integers

Image Analyst
on 18 Sep 2013

Use sprintf to create your string, and cast your numbers to integers or use %.0f:

textString = sprintf('Object: %d, %d (coordinates)', int32(X), int32(Y));
on 18 Sep 2013


Answer by Walter Roberson
on 18 Sep 2013

ndgrid() of 1:width and 1:height, do a logical indexing of those according to the binary image, calculate the mean() of what is left in each of the two coordinate matrices. Result will be centre of mass along each of the two coordinates.


Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply today