Draw line to connect centroids

4 views (last 30 days)
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:
  1. Find centroid from every object.
  2. Draw line to connect each centroids.
  3. 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.

Accepted Answer

Walter Roberson
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-')
  1 Comment
Septian Sukmana
Septian Sukmana on 28 May 2015
Thanks, it helps me.. although I gave wrong method about how to calculate the angel ( I found it after I posted this posting), but It doesn't matter.. I can handle it by myself.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!