【问题标题】:Get rectangle coordinates from a point and a line从点和线获取矩形坐标
【发布时间】:2018-04-01 12:02:59
【问题描述】:

我有[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;

【问题讨论】:

标签: matlab geometry coordinates


【解决方案1】:

[x1, y1][x2, y2] (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;


请注意,通过所有这些重复操作,将您的 xy 值存储在数组中而不是作为单独的变量可能会更整洁。

另外,没有理由使用round,它只会降低结果的准确性。如果您因为要显示值而进行四舍五入,请使用sprintf 或按您显示的 进行四舍五入,而不是在计算之前。

【讨论】:

    【解决方案2】:

    矢量方法使用点 P3 到 P1P2 线上的投影,适用于矩形的任何旋转(注意轴对齐矩形不存在斜率)

      P4 = P1 + (P2 - P1) * DotProduct(P3 - P1, P2 - P1) / DotProduct(P2 - P1, P2 - P1)
      Pa = P1 + (P3 - P4)
      Pb = P2 + (P3 - P4)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      • 2017-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-27
      • 2015-07-03
      相关资源
      最近更新 更多