Find the intersection between object boundaries and a line
2 views (last 30 days)
Show older comments
Ghada Alzamzmi
on 14 Aug 2020
Answered: Ghada Alzamzmi
on 2 Sep 2020
I have a binary mask and a line that passes through the mask as shown in the attached figure. I want to find the intersection point between the mask and the line (the red plus point in the figure).
Can you please help me with this?
I have a binary mask and a line that passes through the mask as shown in the attached figure. I want to find the intersection point between the mask and the line (the red plus point in the figure).
Can you please help me with this?
This is the code to generate the output image:
mask = imread(‘mask.png’);
bw = bwareafilt(im2bw(mask));
s = regionprops(bw, 'Centroid', 'Extrema');
corners = s.Extrema;
Pt1dx = (corners(4,1) + corners(5,1))/2;
Pt1dy = (corners(4,2) + corners(5,2))/2;
Pt2dx = s.Centroid(1);
Pt2dy = s.Centroid(2);
figure;
imshow(bw);
hold on;
plot(Pt1dx, Pt1dy, 'g+');
slope = (Pt1dy-Pt2dy)/(Pt1dx-Pt2dx);
Targetdx = -75.590551181 * cos(slope) + Pt1dx;
Targetdy = -75.590551181 * sin(slope) + Pt1dy;
hold on;
plot(Targetdx, Targetdy, 'b*');
hold on;
line([Pt1dx, Pt1dy], [Targetdx, Targetdy])
hold on;
slopeInv = -1/slope;
xLine = 1:size(bw,2);
yLine = slopeInv.*(xLine - Targetdx) + Targetdy;
plot(xLine, yLine, 'b'); %# Plot the perpendicular line
2 Comments
Image Analyst
on 15 Aug 2020
Yes, but what about the input image mask.png. You forgot to attach that.
Accepted Answer
More Answers (1)
Matt J
on 14 Aug 2020
Edited: Matt J
on 14 Aug 2020
B=cell2mat(bwboundaries(bw,8,'noholes'));
[x,y]=deal(B(:,2),size(bw,1)+1-B(:,1));
[d,loc]=min( abs( slopeInv.*(x - Targetdx) + Targetdy -y) );
intersection = [x(loc), y(loc)]
2 Comments
Matt J
on 15 Aug 2020
Edited: Matt J
on 15 Aug 2020
I don't know what general criterion you use to define the "correct side". This version looks for the intersection with the largest y-coordinate:
B = cell2mat(bwboundaries(bw,8,'noholes'));
[x,y]=deal(B(:,2),size(bw,1)+1-B(:,1));
[a,b,c]=deal(slopeInv,-1, Targetdy-slopeInv.*Targetdx);
loc = abs( (a*x+b*y+c)/norm([a,b]) ) <= sqrt(2)*1.0001;
[~,ymax]=max( y(loc) );
intersection = [x(loc(ymax)), y(loc(ymax))];
hold on
plot(intersection1(1), intersection1(2), 'g+');
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!