import numpy as np
def get_intersect(a1, a2, b1, b2):
"""
Returns the point of intersection of the lines passing through a2,a1 and b2,b1.
a1: [x, y] a point on the first line
a2: [x, y] another point on the first line
b1: [x, y] a point on the second line
b2: [x, y] another point on the second line
"""
s = np.vstack([a1,a2,b1,b2]) # s for stacked
h = np.hstack((s, np.ones((4, 1)))) # h for homogeneous
l1 = np.cross(h[0], h[1]) # get first line
l2 = np.cross(h[2], h[3]) # get second line
x, y, z = np.cross(l1, l2) # point of intersection
if z == 0: # lines are parallel
return (float('inf'), float('inf'))
return (x/z, y/z)
if __name__ == "__main__":
print get_intersect((0, 1), (0, 2), (1, 10), (1, 9)) # parallel lines
print get_intersect((0, 1), (0, 2), (1, 10), (2, 10)) # vertical and horizontal lines
print get_intersect((0, 1), (1, 2), (0, 10), (1, 9)) # another line for fun
Explanation
Note that the equation of a line is ax+by+c=0
. So if a point is on this line, then it is a solution to (a,b,c).(x,y,1)=0
(.
is the dot product)
let l1=(a1,b1,c1)
, l2=(a2,b2,c2)
be two lines and p1=(x1,y1,1)
, p2=(x2,y2,1)
be two points.
Finding the line passing through two points:
let t=p1xp2
(the cross product of two points) be a vector representing a line.
We know that p1
is on the line t
because t.p1 = (p1xp2).p1=0
.
We also know that p2
is on t
because t.p2 = (p1xp2).p2=0
. So t
must be the line passing through p1
and p2
.
This means that we can get the vector representation of a line by taking the cross product of two points on that line.
Finding the point of intersection:
Now let r=l1xl2
(the cross product of two lines) be a vector representing a point
We know r
lies on l1
because r.l1=(l1xl2).l1=0
. We also know r
lies on l2
because r.l2=(l1xl2).l2=0
. So r
must be the point of intersection of the lines l1
and l2
.
Interestingly, we can find the point of intersection by taking the cross product of two lines.