How to find centroids of each line (matrix) from an image

5 views (last 30 days)
Hello folks, I got confused to find a centroid of each line(matrix) from my image.
I made codes to find the length of each line (the white area):
if true
% for i = 1:512
L(i)=0;
for j = 1:256
if D(i,j)==1
L(i)=[L(i)+1];
stats = regionprops(L(i),{'Centroid'});
struct(stats);
end
end
end
end
then i got the length of each line (white matrix), but i dont know how to find centroid for each line. Anyone could help? Thank you so much.

Answers (1)

Walter Roberson
Walter Roberson on 22 Jan 2016
In the special case where the matrix consists of only 0 and 1, then
weights = repmat(1:size(YourMatrix,2), size(YourMatrix,1), 1) .* YourMatrix;
centroid_per_row = sum(weights,2) ./ sum(YourMatrix,2);
The first of these lines creates a matrix of column numbers, and then zeros out the column number in any position where the matrix has a zero value.
The second of these lines takes the mean of the non-zero values from that masked column number matrix. The mean is the sum of the values divided by the number of values, and the number of values corresponds to the number of non-zero values in the row, which in turn corresponds to the sum of the original values in the row (under the assumption that the original values are only 0 and 1)
The centroid is the mean of the coordinates at which there is an image present.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!