I'm using Python+Numpy (can maybe also use Scipy) and have three 2D points
(P1, P2, P3);
I am trying to get the distance from P3 perpendicular to a line drawn between P1 and P2. Let P1=(x1,y1), P2=(x2,y2) and P3=(x3,y3)
In vector notation this would be pretty easy, but I'm fairly new to python/numpy and can't get anythng that works (or even close).
Any tips appreciated, thanks!
Try using the norm function from numpy.linalg
d = norm(np.cross(p2-p1, p1-p3))/norm(p2-p1)
np.cross returns the z-coordinate of the cross product only for 2D vectors. So the first norm in the accepted answer is not needed, and is actually dangerous if p3 is an array of vectors rather than a single vector. Best just to use
d=np.cross(p2-p1,p3-p1)/norm(p2-p1)
which for an array of points p3 will give you an array of distances from the line.
For the above-mentioned answers to work, the points need to be numpy arrays, here's a working example:
import numpy as np
p1=np.array([0,0])
p2=np.array([10,10])
p3=np.array([5,7])
d=np.cross(p2-p1,p3-p1)/np.linalg.norm(p2-p1)
To find distance to line from point if you have slope and intercept you can use formula from wiki
https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line
Python:
def distance(point,coef):
return abs((coef[0]*point[0])-point[1]+coef[1])/math.sqrt((coef[0]*coef[0])+1)
coef is a tuple with slope and intercept
Based on the accepted answer
Test with below line equation -
Find the perpendicular distance from the point (5, 6) to the line −2x + 3y + 4 = 0
x-intercept p1 = [0, -4/3]
y-intercept p2 = [2, 0]
shortest distance from p3 = [5, 6] = 3.328
import numpy as np
norm = np.linalg.norm
p1 = np.array([0,-4/3])
p2 = np.array([2, 0])
p3 = np.array([5, 6])
d = np.abs(norm(np.cross(p2-p1, p1-p3)))/norm(p2-p1)
# output d = 3.328201177351375
abs((x2-x1)*(y1-y0) - (x1-x0)*(y2-y1)) / np.sqrt(np.square(x2-x1) + np.square(y2-y1))
Can be used directly through the formula, just have to plug in the values and boom it will work.
Shortest Distance from Point to a Line
This is the code I got from https://www.geeksforgeeks.org:
import math
# Function to find distance
def shortest_distance(x1, y1, a, b, c):
d = abs((a * x1 + b * y1 + c)) / (math.sqrt(a * a + b * b))
print("Perpendicular distance is", d)
Now you have to find A, B, C, x, and y.
import numpy as np
closest = []
x = (x ,y)
y = (x, y)
coef = np.polyfit(x, y, 1)
A = coef[0]
B = coef[1]
C = A*x[0] + B*x[1]
Now you can plug in the values:
shortest_dis = shortest_distance(x, y, A, B, C)
The full code may look like this:
import math
import numpy as np
def shortest_distance(x1, y1, a, b, c):
d = abs((a * x1 + b * y1 + c)) / (math.sqrt(a * a + b * b))
print("Perpendicular distance is", d)
closest = []
x = (x ,y)
y = (x, y)
coef = np.polyfit(x, y, 1)
A = coef[0]
B = coef[1]
C = A*x[0] + B*x[1]
shortest_dis = shortest_distance(x, y, A, B, C)
Please let me know if any of this is unclear.
Cross products are helpful for the 2D case, but they do not generalize well to other dimensions. Dot products do however. The dot product of two orthogonal vectors is zero in any space, which you can use to come up with a simple solution.
Let's say you have P4 on the same line as P1-P2. You could parametrize it with parameter t such that
P4 = P1 + t * (P2 - P1)
The goal is to find P4 such that
(P3 - P4) . (P2 - P1) == 0
Expanding P4 in terms of t and simplifying:
(P3 - P1 - t * (P2 - P1)) . (P2 - P1) == 0
(P3 - P1) . (P2 - P1) == t * ||P2 - P1||^2
t = (P3 - P1) . (P2 - P1) / ||P2 - P1||^2
You therefore have
D = ||P3 - P4|| = ||P3 - (P3 - P1) . (P2 - P1) / (||P2 - P1||^2)||
I've written a function in my library of utility routines called haggis. You can use haggis.math.segment_distance to compute the distance to the entire line (not just the bounded line segment) like this:
d = haggis.math.segment_distance(P3, P1, P2, segment=False)
3D distance should use np.dot
def threeD_corres(points_3_d,pre_points_3_d,points_camera):
for j in range (0,len(pre_points_3_d)):
vec1 = list(map(lambda x:x[0]- x[1],zip(pre_points_3_d[j], points_camera)))
vec2 = list(map(lambda x:x[0]- x[1],zip(pre_points_3_d[j], points_3_d[j])))
vec3 = list(map(lambda x:x[0]- x[1],zip(points_3_d[j], points_camera)))
distance = np.abs(np.dot(vec1_1,vec2_2))/np.linalg.norm(vec3)
print("#########distance:\n",distance)
return distance
Related
The line is not a line segment, but should extend to infinity. I tried using this guys answer but I just got nan's because I was dividing by 0. Preferably I want something quick and easy with dot and cross products and such.
x = np.array([-1,-1,-1])
y = np.array([4,4,4])
a = np.array([2,2,2])
epsilon = 0.0001
#algorithm
print((x[2] - x[0]) / (x[1] - x[0]))
print((y[2] - y[0]) / (y[1] - y[0]))
print((a[2] - a[0]) / (a[1] - a[0]))
Ouput:
nan
nan
nan
Here is one possibility, depending on the application the code can be simplified, but I preferred to give a solution with a clear interpretation rather than a clear code.
def colinear(p1, p2, p3, rtol=1e-5):
'''
Test colinearity making sure that sin(angle) < rtol
'''
# twice the area of the triangle (p1, p2, p3)
A = np.linalg.norm(np.cross(p2 - p1, p3 - p1))
# length of two sides meeting the vertice p1
a = np.linalg.norm(p2 - p1)
b = np.linalg.norm(p3 - p1)
c = np.linalg.norm(p2 - p3)
# pick the two largest sides
_, a, b = sorted([a,b,c])
# the angle at the vertice where those points meet
# will be A / (a * b)
return A < rtol * a * b
x = np.array([-1,-1,-1])
y = np.array([4,4,4])
a = np.array([2,2,2])
assert colinear(x, y, a)
I am working on a python script and I am sure there is an easier way to approach this problem then my solution so far.
Give two coordinates, say (0,0) and (40,40) and a set distance to travel, say 5, how would I find a new coordinate pair for the point that is 5 units from (0,0) heading along the line that connects (0,0) and (40,40)?
I am doing the following given the distance_to_travel and points p0, p1:
ang = math.atan2(p1.y - p0.y, p1.x - p0.x)
xx = node0.x + (distance_to_travel * math.cos(ang))
yy = node0.y + (distance_to_travel * math.sin(ang))
Following the method outlined in my comment:
# find the vector a-b
ab.x, ab.y = p1.x - p0.x, p1.y - p0.y
# find the length of this vector
len_ab = (ab.x * ab.x + ab.y * ab.y) ** 0.5
# scale to length 5
ab5.x, ab5.y = ab.x *5 / len_ab, ab.y *5 / len_ab
# add to a (== p0)
fin.x, fin.y = p0.x + ab5.x, p0.y + ab5.y
You should find the slope of the line between a and b |ab|.
Then you can use 2D spherical (polar) coordinate system to get r mount of distance with a given slope (The slope you found earlier).
Now you can convert from spherical to Cartesian to find x, y coordinates of new point. Then you add this values to values of point a:
import math
def slope(p1, p2):
return math.atan2(
(p2[1] - p1[1]), (p2[0] - p1[0])
)
def spherical_to_cartesian(r, theta):
x = r * math.cos(theta)
y = r * math.sin(theta)
return x, y
def add_points(p1, p2):
return p1[0] + p2[0], p1[1] + p2[1]
if __name__ == '__main__':
a = [0, 0]
b = [40, 40]
slp = slope(a, b)
r = 5
new_p = spherical_to_cartesian(r, slp)
res = add_points(a, new_p)
print(res)
For a straight line, Slope k is known, one point(x1,y1) is know, how to get the other point (x2,y2) using python?
I know the way to do calculation, but have no idea to code using python.
(y2-y1)/(x2-x1)=k
sqrt((x2-x1)^2+(y2-y1)^2)= length
if two unknown equations, both two variables with power 1, linalg-solve should work, but now the power of 2rd function is 2, how to deal with that?
I tried to simplify as following, but seems I cannot apply linalg-solve
kx2-y2-kx1+y1 = 0
(y2-y1)^2 + (x2-x1)^2 = length^2
Supplement:
thanks to all of your answer...Posh_Pumpkin's code is exactly what I want, previously I thought I need to apply linalg-solve which I usually use.
here is a test code based on his answer:suppose P1 = (1,1) p2=(x,y), p1p2= sqrt(2), k=1,then p2 must be = (2,2)
import numpy as np
import math
k = 1
d = math.sqrt(2)
p1 = (1,1)
r_sq = d**2 / (1 + k**2)
r = math.sqrt(r_sq)
p2 = (p1[0] + r, p1[1] + k*r)
print(p2)
Why use a complicated solution at all? I would approach it under the assumption that P1 = (0, 0).
Assuming P1 is at the origin, and knowing that the slope = k, you know that P2 = (r, k*r) for a constant r. The r can be computed by calculating the distance P1P2. Since you said you already know the distance, we can then simply do:
r^2 + (k*r)^2 = d^2
To find r. Once you find r, you can get the coordinates of P2 when P1 = (0, 0). So to find the actual coordinates, you'd just do P2 = P1 + P2. Check below:
import math
# Obviously assume k and d are known constants, and P1 is a known point
k = # given k
d = # given d
p1 = # (given x coord, given y coord)
r_sq = d**2 / (1 + k**2)
r = math.sqrt(r_sq)
p2 = (p1[0] + r, p1[1] + k*r)
print(p2)
If you have to use numpy, you should show us your code and what exactly is troubling you. What is preventing you from using the module, whether it's an error or an unexpected behavior?
You can solve this with basic trig. Here is the general derivation.
let p1 = (x1,y1) & p2 = (x2 = x1+d, y2 = y1+h),
let L be the distance between p1 & p2
* note for p1 & p2 such that x1 != x2 && y1 != y2, a triangle can be formed Ldh such that tan(theta) = h/d
h/d is the slope of the line (m) connecting points p1 & p2, so tan(theta) = m
=> theta = atan(m), from the law of sines ( sin(a)/A = sin(b)/B )
=> sin(90)/L = sin(atan(theta))/y2
=> y2 = L*sin( atan(theta) )
now get x from the point slope form of a line y= y1+m(x-x1) = (y-y1)/m +x1
so x2 = (y2-y1)/m + x1
Here is this expressed in python:
from math import sin, atan
from random import randint
# This is the formula for (x2,y2) = p2
x = lambda y2, m, x1, y1: (y2 - y1)/float(m) + x1
y = lambda l, m, y1: l*sin( atan(m) ) + y1
# p2 constraints ( x2 > x1, y2 > y1 or x2 > x1, y2 < y1 )
p1 = [randint(1,1000),randint(1,1000)]
p2 = [randint(p1[0],1001),randint(0,p1[1])]
# calculate distance between p1 & p2 (L), also calculate slope (m)
slope = lambda x1,y1,x2,y2: (y2-y1)/float(x2-x1)
dist = lambda x1,y1,x2,y2: ( (y2-y1)**2 + (x2-x1)**2 )**(0.5)
L = dist(p1[0],p1[1],p2[0],p2[1])
m = slope(p1[0],p1[1],p2[0],p2[1])
# now see if our functions for x & y yield p2
y2 = y(L,m,p1[1])
p_derived = [ x(y2,m,p1[0],p1[1]),y2 ]
print "p1: ",p1 , "p2 actual: ",p2, "p2 derived: ",p_derived
So here I generate two random points p1 and p2, and verify that p2 can be calculated from the slope, distance, and p1 by comparing my derived result to the actual result.
Given 3 points in space (3D): A = (x1, y1, z1), B = (x2, y2, z2) C = (x3, y3, z3); then how to find the center and radius of the circle (arc) that passes through these three points, i.e. find circle equation? Using Python and Numpy here is my initial code
import numpy as np
A = np.array([x1, y1, z1])
B = np.array([x2, y2, z2])
C = np.array([x3, y3, z3])
#Find vectors connecting the three points and the length of each vector
AB = B - A
BC = C - B
AC = C - A
# Triangle Lengths
a = np.linalg.norm(AB)
b = np.linalg.norm(BC)
c = np.linalg.norm(AC)
From the Circumradius definition, the radius can be found using:
R = (a * b * c) / np.sqrt(2.0 * a**2 * b**2 +
2.0 * b**2 * c**2 +
2.0 * c**2 * a**2 -
a**4 - b**4 - c**4)
However, I am having problems finding the Cartesian coordinates of the center. One possible solution is to use the "Barycentric Coordinates" of the triangle points to find the trilinear coordinates of the circumcenter (Circumcenter).
First (using this source) we find the circumcenter barcyntric coordinates:
#barcyntric coordinates of center
b1 = a**2 * (b**2 + c**2 - a**2)
b2 = b**2 * (c**2 + a**2 - b**2)
b3 = c**2 * (a**2 + b**2 - c**2)
Then the Cartesian coordinates of the center (P) would be:
Px = (b1 * A[0]) + (b2 * B[0]) + (b3 * C[0])
Py = (b1 * A[1]) + (b2 * B[1]) + (b3 * C[1])
Pz = (b1 * A[2]) + (b2 * B[2]) + (b3 * C[2])
However, the barcyntric coordinates values above do not seem to be correct. When solved with an example of known values, the radius is correct, but the coordinates of the center are not.
Example: For these three points:
A = np.array([2.0, 1.5, 0.0])
B = np.array([6.0, 4.5, 0.0])
C = np.array([11.75, 6.25, 0.0])
The radius and center coordinates are:
R = 15.899002930062595
P = [13.4207317073, -9.56097560967, 0]
Any ideas on how to find the center coordinates?
There are two issues with your code.
The first is in the naming convention. For all the formulas you are using to hold, the side of length a has to be the one opposite the point A, and similarly for b and B and c and C. You can solve that by computing them as:
a = np.linalg.norm(C - B)
b = np.linalg.norm(C - A)
c = np.linalg.norm(B - A)
The second has to do with the note in your source for the barycentric coordinates of the circumcenter: not necessarily homogeneous. That is, they need not be normalized in any way, and the formula you are using to compute the Cartesian coordinates from the barycentric ones is only valid when they add up to one.
Fortunately, you only need to divide the resulting Cartesian coordinates by b1 + b2 + b3 to get the result you are after. Streamlining a little bit your code for efficiency, I get the results you expect:
>>> A = np.array([2.0, 1.5, 0.0])
>>> B = np.array([6.0, 4.5, 0.0])
>>> C = np.array([11.75, 6.25, 0.0])
>>> a = np.linalg.norm(C - B)
>>> b = np.linalg.norm(C - A)
>>> c = np.linalg.norm(B - A)
>>> s = (a + b + c) / 2
>>> R = a*b*c / 4 / np.sqrt(s * (s - a) * (s - b) * (s - c))
>>> b1 = a*a * (b*b + c*c - a*a)
>>> b2 = b*b * (a*a + c*c - b*b)
>>> b3 = c*c * (a*a + b*b - c*c)
>>> P = np.column_stack((A, B, C)).dot(np.hstack((b1, b2, b3)))
>>> P /= b1 + b2 + b3
>>> R
15.899002930062531
>>> P
array([ 13.42073171, -9.56097561, 0. ])
As an extension to the original problem: Now suppose we have an arc of known length (e.g. 1 unit) extending from point A as defined above (away from point B). How to find the 3D coordinates of the end point (N)? The new point N lies on the same circle passing through points A, B & C.
This can be solved by first finding the angle between the two vectors PA & PN:
# L = Arc Length
theta = L / R
Now all we need to do is rotate the vector PA (Radius) by this angle theta in the correct direction. In order to do that, we need the 3D rotation matrix. For that we use the Euler–Rodrigues formula:
def rotation_matrix_3d(axis, theta):
axis = axis / np.linalg.norm(axis)
a = np.cos(theta / 2.0)
b, c, d = axis * np.sin(theta / 2.0)
rot = np.array([[a*a+b*b-c*c-d*d, 2*(b*c-a*d), 2*(b*d+a*c)],
[ 2*(b*c+a*d), a*a+c*c-b*b-d*d, 2*(c*d-a*b)],
[ 2*(b*d-a*c), 2*(c*d+a*b), a*a+d*d-b*b-c*c]])
return rot
Next, we need to find the rotation axis to rotate PA around. This can be achieved by finding the axis normal to the plane of the circle passing through A, B & C. The coordinates of point N can then be found from the center of the circle.
PA = P - A
PB = P - B
xx = np.cross(PB, PA)
r3d = rotation_matrix_3d(xx, theta)
PN = np.dot(r3d, PA)
N = P - PN
as an example, we want to find coordinates of point N that are 3 degrees away from point A, the coordinates would be
N = (1.43676498, 0.8871264, 0.)
Which is correct! (manually verified using CAD program)
I've already posted this question about this topic:
Speeding up a closest point on a hyperbolic paraboloid algorithm
Given four points (p0,p1,p2,p3) to define a doubly ruled hyperbolic paraboloid, what is the best (fastest) way to compute its surface area using python's numpy module?
This is more maths than programming, so you may want to check with the folks at math.stackexchange. But, from the answer to your previous question, the surface can be parametrized as:
s = p0 + u * (p1 - p0) + v * (p3 - p0) + u * v * (p2 - p3 - p1 + p0) =
p0 + u * a + v * b + u * v * c
with the area limited by your four points being 0 <= u <= 1 and 0 <= v <= 1.
You can get two vectors tangent to the surface by differentiation:
t1 = ds/du = a + v * c
t2 = ds/dv = b + u * c
And you can get a vector, perpendicular to the other two, with a norm equal to the area of the parallelogram described by them, taking their cross product:
A = t1 x t2 = a x b + u * a x c + v * c x b
It is tempting to simply go ahead and integrate A, but it is its norm you want to integrate, not the vector itself. I have tried feeding that to Mathematica, to see if it would come up with some nice, closed form solution, but it's been going for several minutes now without arriving anywhere. So you may as well do things numerically:
def integrate_hypar(p0, p1, p2, p3, n=100):
a = p1 - p0
b = p3 - p0
c = p2 - p3 - p1 + p0
delta = 1 / n
u = np.linspace(0,1, num=n, endpoint=False) + delta / 2
axb = np.cross(a, b)
axc = np.cross(a, c)
cxb = np.cross(c, b)
diff_areas = (axb + u[:, None, None] * axc +
u[:, None] * cxb) * delta * delta
diff_areas *= diff_areas
diff_areas = np.sum(diff_areas, axis=-1)
diff_areas = np.sqrt(diff_areas)
return np.sum(diff_areas)
With the data points from your other question, I get:
p0 = np.array([1.15, 0.62, -1.01])
p1 = np.array([1.74, 0.86, -0.88])
p2 = np.array([1.79, 0.40, -1.46])
p3 = np.array([0.91, 0.79, -1.84])
>>> integrate_hypar(p0, p1, p2, p3)
0.54825122958719719