[英]Get rectangle coordinates from a point and a line
我有3点[x1,y1]
, [x2,y2]
和[x3,y3]
的坐标,如下所示。
它们定义了一条线,该线是矩形的一侧,而点则位于矩形的平行/相对侧。 我想获取其他两个角的坐标。
如图所示,如何计算点[xa, ya]
和[xb, yb]
?
clc;
clear;
I = imread('peppers.png');
imshow(I);
h = imline;
lineEndPoints = wait(h);
x1 = round(lineEndPoints(1,1),2);
y1 = round(lineEndPoints(1,2),2);
x2 = round(lineEndPoints(2,1),2);
y2 = round(lineEndPoints(2,2),2);
hold on
[x3, y3] = ginput(1);
plot(x3, y3,'b*');
slope = (y2 - y1)/ (x2 - x1);
slopePerp = -1/slope;
您具有[x1, y1]
和[x2, y2]
slope
( slope
)以及与[x3, y3]
垂直线的斜率( slopPerp
)。
因此,您对[x1, y1]
到[x2, y2]
行的y截距为
% From y=mx+c -> c=y-mx
c = y1 - slope*x1;
您还可以获得通过[x3, y3]
的垂直线的y截距
cPerp = y3 - slopePerp*x3;
然后,两条黑线相交的点称为[x4,y4]
为
% Simultaneous equations
% y = slope*x + c
% y = slopePerp*x + cPerp
% slope*x + c = slopePerp*x + cPerp
% x*(slope - slopePerp) = cPerp - c
x4 = (cPerp - c) / (slope - slopePerp);
y4 = slope*x4 + c;
现在我们需要的是x和y的差异
xdiff = x3 - x4; % So x4 + xdiff = x3
ydiff = y3 - y4; % So y4 + xdiff = y3
并将这些加到我们的1分和2分
xa = x1 + xdiff;
ya = y1 + ydiff;
xb = x2 + xdiff;
yb = y2 + ydiff;
请注意,通过所有这些重复的操作,将x
和y
值存储在数组中而不是将其存储为单独的变量可能更整洁。
另外,没有理由使用round
,这只会使结果不那么准确。 如果你是四舍五入,因为你要显示的值,使用sprintf
或圆形为您显示,不计算之前。
向量方法使用点P3在线P1P2上的投影,并且可以对矩形进行任何旋转(请注意,与轴对齐的矩形不存在斜率)
P4 = P1 + (P2 - P1) * DotProduct(P3 - P1, P2 - P1) / DotProduct(P2 - P1, P2 - P1)
Pa = P1 + (P3 - P4)
Pb = P2 + (P3 - P4)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.