File Exchange

image thumbnail

Center of Mass

version 1.0 (1.92 KB) by

CENTEROFMASS finds the center of mass of the N-dimensional input array



View License

centerOfMass(A) finds the gray-level-weighted center of mass of the
N-dimensional numerical array A. A must be real and finite. A warning
is issued if A contains any negative values. Any NaN elements of A will
automatically be ignored. centerOfMass produces center of mass
coordinates in units of pixels. An empty array is returned if the
center of mass is undefined.

The center of mass is reported under the assumption that the first
pixel in each array dimension is centered at 1.

Also note that numerical arrays other than DOUBLE and SINGLE are
converted to SINGLE in order to prevent numerical roundoff error.

A = rgb2gray(imread('saturn.png'));
C = centerOfMass(A);

figure; imagesc(A); colormap gray; axis image
hold on; plot(C(2),C(1),'rx')

Comments and Ratings (6)

F. Jacobs

F. Jacobs

Trevor Agus

Shaiq Ghorwal

Thank you for this useful script.

I've figured out that by doing a few manipulations then the script is also able to find the geometric center of mass of a 3D HOMOGENEOUS object, assuming it is SYMMETRIC around any of the 3 dimensions: x, y or z.

Say the image file is called image.png, and EVERYTHING in the image, apart from the object of interest, is totally bright, meaning it has pixel value 255, then here is what you need to do:

A = rgb2gray(imread('image.png'));
A(A==255) = NaN;
color = 50;
A(A>0) = color;

C = centerOfMass(A);

% the value of color can be in principle
anything between 0 and 255. If it is close to 50, then you are able to see the image..


Kahye (view profile)

Lena Veis

You save me a lot of time...
Thank you very much :)

MATLAB Release
MATLAB 8.1 (R2013a)

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video