File: ef230-2023-08/www/examples/center_mass_image.m Download
%|Compute the center of mass of an image
%|by treating each pixel as a point mass
function center_mass_image(file)
clc;
close all;
% set default image if no input
if nargin==0
    file='screenshot.png';
end
% get the image
im = imread(file);
% convert to B/W
imbw = im2bw(im,.9)
% flip white/black
imbw=~imbw;
% get number of rows and columns
[nr,nc]=size(imbw)
% init counters
x=0; y=0; t=0;
% loop through pixels
for r=1:nr
    for c=1:nc
        x=x+c.*imbw(r,c); % weighted x
        y=y+r.*imbw(r,c); % weighted y
        t=t+imbw(r,c);    % total
    end
end
% calc final results
x=x/t;
y=y/t;

% show results
image(imbw)
axis equal
set(gca,'color',[.7 .7 .7])
colormap([0 0 0; 1 1 1])
hold on
grid on
plot(x,y,'ro')