clear; close all; clc
% load downloaded image
img = imread('centroid.jpg');
% crop the plotted part
%img = img(32:374, 74:507, :);
% threshold the image
gray = rgb2gray(img);
bin = gray > 65;
% number of pixels above threshold in each column
colwgt = sum(bin);
% number of pixels above threshold in each row
rowwgt = sum(bin, 2)';
% number of pixels above threshold
wgt = sum(bin(:));
% vertical position of the centroid
x = sum(colwgt .* (1:length(colwgt))) / wgt;
% horizontal position of the centroid
y = sum(rowwgt .* (1:length(rowwgt))) / wgt;
% visualize the result
img = insertMarker(img, [x y]);
imshow(img)