Draw line to connect centroids
4 views (last 30 days)
Show older comments
Septian Sukmana
on 27 May 2015
Commented: Septian Sukmana
on 28 May 2015
Hi everybody, I need your help with my problem. Actually I'm new in Matlab. I have an image
I want to find centroid from each objects, then connect these centroids with line, the measure the angle. To be more detail, here is my steps:
- Find centroid from every object.
- Draw line to connect each centroids.
- measure the angle (marked area).
I have achieved the first step by using this code (Thanks to Image Analyst)
I = imread('22c.jpg');
Ibw = im2bw(I);
Ibw = imfill(Ibw,'holes');
Ilabel = bwlabel(Ibw);
stat = regionprops(Ilabel,'centroid');
imshow(I); hold on;
for x = 1: numel(stat)
plot(stat(x).Centroid(1),stat(x).Centroid(2),'ro');
end
To be more clear, here is my goal
The problem is I am still confused to do the next (to connect each centroids and measure the angle). I need your help, thanks.
0 Comments
Accepted Answer
Walter Roberson
on 27 May 2015
The ease of doing this is going to depend upon the assumptions that can be made. Will the pair of bones always be more or less vertical, or could they be horizontal? And even if vertical, is it ever possible that the centroid of the square belonging to the upper bone be below the centroid of the square belonging to the lower bone?
If you can rely upon the y axis serving to sort the centroids, then,
C = vertcat(stat.Centroid);
Csorted = sortrows(C); %each coordinate is a (Y,X) pair and we sort on Y
plot(Csorted(:,1), CSorted(:,2), 'ro-');
Your instructions are to calculate the angle of the line, but there are really two angles: the angle for Bone1-Pin1-Pin2 and the angle for Pin1-Pin2-Bone2.
%A . B = ||A|| * ||B|| * cos(theta)
cdiff = diff(Csorted,1); %coordinates into vectors
c_mags = sqrt(sum(cdiff.^2,2)); %distance first to second, second to third, etc
c_mag_prods = c_mags(1:end-1) .* c_mags(2:end); %||A|| * ||B||
c_dots = dot(cdiff(1:end-1,:), cdiff(2:end,:), 2); %dot products
costheta = c_dots ./ c_mag_prods; %isolate cos
theta = acos(costheta); %in radians!
theta_deg = theta * 180/Pi; %in degrees
For example with Csorted = [2 9;8 6;9 6;10 2] then the calculation comes out as about 26.5 degrees for the first angle and about 76 degrees for the second angle, which visually looks reasonable on
plot([2 8 9 10],[9 6 6 2],'ro-')
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!