How to find centroids of each line (matrix) from an image
3 views (last 30 days)
Show older comments
Hello folks, I got confused to find a centroid of each line(matrix) from my image.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/153477/image.jpeg)
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.
0 Comments
Answers (1)
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)
0 Comments
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!