簡體   English   中英

從點和線獲取矩形坐標

[英]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] slopeslope )以及與[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或圓形您顯示,不計算之前。

向量方法使用點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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM