简体   繁体   English

从点和线获取矩形坐标

[英]Get rectangle coordinates from a point and a line

I have the coordinates of 3 points [x1,y1] , [x2,y2] and [x3,y3] as shown below. 我有3点[x1,y1][x2,y2][x3,y3]的坐标,如下所示。

They define the line which is one side of a rectangle, and a point which lies on the parallel/opposite side of the rectangle. 它们定义了一条线,该线是矩形的一侧,而点则位于矩形的平行/相对侧。 I want to get the coordinates of the other two corners. 我想获取其他两个角的坐标。

How can I calculate points [xa, ya] and [xb, yb] as shown? 如图所示,如何计算点[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;

You have the slope between [x1, y1] and [x2, y2] ( slope ) and the slope for the perpendicular line to [x3, y3] ( slopPerp ). 您具有[x1, y1][x2, y2] slopeslope )以及与[x3, y3]垂直线的斜率( slopPerp )。

So you have the y-intercept for the line [x1, y1] to [x2, y2] as 因此,您对[x1, y1][x2, y2]行的y截距为

% From y=mx+c -> c=y-mx
c = y1 - slope*x1;

You can also get the y-intercept of the perpendicular line passing through [x3, y3] 您还可以获得通过[x3, y3]的垂直线的y截距

cPerp = y3 - slopePerp*x3;

Then the point where your two black lines meet, let's call it [x4,y4] is 然后,两条黑线相交的点称为[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;

Now all we need is the x and y differences 现在我们需要的是x和y的差异

xdiff = x3 - x4; % So x4 + xdiff = x3
ydiff = y3 - y4; % So y4 + xdiff = y3

And to add these to our 1 and 2 points 并将这些加到我们的1分和2分

xa = x1 + xdiff;
ya = y1 + ydiff;
xb = x2 + xdiff;
yb = y2 + ydiff;

图片


Note, with all these repeated actions it would probably be neater to store your x and y values in arrays rather than as separate variables. 请注意,通过所有这些重复的操作,将xy值存储在数组中而不是将其存储为单独的变量可能更整洁。

Also, there is no reason to be using round , it will only make the result less accurate. 另外,没有理由使用round ,这只会使结果不那么准确。 If you are rounding because you want to display the values, use sprintf or round as you display, not before calculations. 如果你是四舍五入,因为你要显示的值,使用sprintf或圆形您显示,不计算之前。

Vector approach uses projection of point P3 onto line P1P2 and works for any rotation of rectangle (note that slope does not exist for axis-aligned rectangle) 向量方法使用点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