Stolen directly from https://web.archive.org/web/20111108065352/https://www.cs.mun.ca/~rod/2500/notes/numpy-arrays/numpy-arrays.html

#
# line segment intersection using vectors
# see Computer Graphics by F.S. Hill
#
from numpy import *
def perp( a ) :
    b = empty_like(a)
    b[0] = -a[1]
    b[1] = a[0]
    return b

# line segment a given by endpoints a1, a2
# line segment b given by endpoints b1, b2
# return 
def seg_intersect(a1,a2, b1,b2) :
    da = a2-a1
    db = b2-b1
    dp = a1-b1
    dap = perp(da)
    denom = dot( dap, db)
    num = dot( dap, dp )
    return (num / denom.astype(float))*db + b1

p1 = array( [0.0, 0.0] )
p2 = array( [1.0, 0.0] )

p3 = array( [4.0, -5.0] )
p4 = array( [4.0, 2.0] )

print seg_intersect( p1,p2, p3,p4)

p1 = array( [2.0, 2.0] )
p2 = array( [4.0, 3.0] )

p3 = array( [6.0, 0.0] )
p4 = array( [6.0, 3.0] )

print seg_intersect( p1,p2, p3,p4)
Answer from Hamish Grubijan on Stack Overflow
Top answer
1 of 12
50

Stolen directly from https://web.archive.org/web/20111108065352/https://www.cs.mun.ca/~rod/2500/notes/numpy-arrays/numpy-arrays.html

#
# line segment intersection using vectors
# see Computer Graphics by F.S. Hill
#
from numpy import *
def perp( a ) :
    b = empty_like(a)
    b[0] = -a[1]
    b[1] = a[0]
    return b

# line segment a given by endpoints a1, a2
# line segment b given by endpoints b1, b2
# return 
def seg_intersect(a1,a2, b1,b2) :
    da = a2-a1
    db = b2-b1
    dp = a1-b1
    dap = perp(da)
    denom = dot( dap, db)
    num = dot( dap, dp )
    return (num / denom.astype(float))*db + b1

p1 = array( [0.0, 0.0] )
p2 = array( [1.0, 0.0] )

p3 = array( [4.0, -5.0] )
p4 = array( [4.0, 2.0] )

print seg_intersect( p1,p2, p3,p4)

p1 = array( [2.0, 2.0] )
p2 = array( [4.0, 3.0] )

p3 = array( [6.0, 0.0] )
p4 = array( [6.0, 3.0] )

print seg_intersect( p1,p2, p3,p4)
2 of 12
33
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.

🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.intersect1d.html
numpy.intersect1d — NumPy v2.5 Manual
If True, the indices which correspond to the intersection of the two arrays are returned. The first instance of a value is used if there are multiple.
Discussions

python - How do I compute the intersection point of two lines? - Stack Overflow
I have two lines that intersect at a point. I know the endpoints of the two lines. How do I compute the intersection point in Python? # Given these endpoints #line 1 A = [X, Y] B = [X, Y] #line... More on stackoverflow.com
🌐 stackoverflow.com
December 19, 2013
python - intersection points of two lines by numpy - Stack Overflow
I would like to have the intersection points of two lines in python using numpy. I wrote a piece of code but I can not complete the code. I have a curve of 1000 points which has been read by numpy ... More on stackoverflow.com
🌐 stackoverflow.com
February 26, 2020
python - Finding coordinate points of intersection with two numpy arrays - Stack Overflow
This sort of question is a tad bit different the normal 'how to find the intersection of two lines' via numpy. Here is the situation, I am creating a program that looks at slope stability and I nee... More on stackoverflow.com
🌐 stackoverflow.com
Line-Line intersection in Python with numpy - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I have a relatively simple question, I know the answer but I can't seem to find the right implementation using Python and Numpy. The idea is, I have two lines and I need to find the virtual intersection ... More on stackoverflow.com
🌐 stackoverflow.com
June 19, 2017
🌐
Reddit
reddit.com › r/learnpython › how to find when a two lines intersect? (numpy, matplotlib, pandas)
r/learnpython on Reddit: How to find when a two lines intersect? (Numpy, matplotlib, pandas)
July 31, 2017 -

I have a few lines that are constantly updating. They represent the price of an asset. I'm looking to figure out how to tell when and where the two lines intersect. They will almost definitely intersect between two points however.

Thanks!

🌐
GitHub
gist.github.com › hellpanderrr › a6c30179f64bb1b13b85
Python find intersection of two vectors using matplotlib and numpy · GitHub
from numpy import dot,array,empty_like from matplotlib.path import Path def make_path(x1,y1,x2,y2): return Path([[x1,y1],[x1,y2],[x2,y2],[x2,y1]]) def perp( a ) : b = empty_like(a) b[0] = -a[1] b[1] = a[0] return b # line segment a given by endpoints a1, a2 # line segment b given by endpoints b1, b2 # return def seg_intersect(a1,a2, b1,b2) : da = a2-a1 db = b2-b1 dp = a1-b1 dap = perp(da) denom = dot( dap, db) num = dot( dap, dp ) x3 = ((num / denom.astype(float))*db + b1)[0] y3 = ((num / denom.astype(float))*db + b1)[1] p1 = make_path(a1[0],a1[1],a2[0],a2[1]) p2 = make_path(b1[0],b1[1],b2[0],b2[1]) if p1.contains_point([x3,y3]) and p2.contains_point([x3,y3]): return x3,y3 else: return False p1 = array( [2.0, 1.0] ) p2 = array( [7.0, 3.0] ) p3 = array( [2.0, 5.0] ) p4 = array( [5.0, 2.0] ) print seg_intersect( p1,p2, p3,p4)
🌐
GitHub
gist.github.com › danieljfarrell › faf7c4cafd683db13cbc
Ray line segment intersection in Python using Numpy · GitHub
Ray line segment intersection in Python using Numpy · Raw · gistfile1.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Moonbooks
moonbooks.org › Articles › How-to-write-a-simple-python-code-to-find-the-intersection-point-between-two-straight-lines-
How to write a simple python code to find the intersection point between two straight lines ?
August 23, 2022 - Example of how to write a simple python code to find the intersection point between two straight lines: ... import matplotlib.pyplot as plt import numpy as np m1, b1 = 1.0, 2.0 # slope & intercept (line 1) m2, b2 = 4.0, -3.0 # slope & intercept (line 2) x = np.linspace(-10,10,500) ...
🌐
NumPy
numpy.org › doc › 2.2 › reference › generated › numpy.intersect1d.html
numpy.intersect1d — NumPy v2.2 Manual
If True, the indices which correspond to the intersection of the two arrays are returned. The first instance of a value is used if there are multiple.
🌐
SukhbinderSingh.com
sukhbinder.wordpress.com › 2017 › 06 › 13 › intersection-of-two-curves-in-pure-numpy
Intersection Of two curves in Pure Numpy – SukhbinderSingh.com
June 10, 2022 - […] most starred GitHub repository, Intersection, is a MATLAB-inspired implementation for finding the intersection of two curves using numpy written in […]
Find elsewhere
🌐
Iditect
iditect.com › faq › python › numpy-and-line-intersections.html
Numpy and line intersections
It calculates the slopes of the lines (m1 and m2) and checks if they are parallel. If the lines are not parallel, it calculates the intersection point. The result is either the intersection point as a tuple (x, y) or None if there is no intersection. This is a simple example, and in more complex ...
Top answer
1 of 13
115

Unlike other suggestions, this is short and doesn't use external libraries like numpy. (Not that using other libraries is bad...it's nice not need to, especially for such a simple problem.)

def line_intersection(line1, line2):
    xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])
    ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1])

    def det(a, b):
        return a[0] * b[1] - a[1] * b[0]

    div = det(xdiff, ydiff)
    if div == 0:
       raise Exception('lines do not intersect')

    d = (det(*line1), det(*line2))
    x = det(d, xdiff) / div
    y = det(d, ydiff) / div
    return x, y

print line_intersection((A, B), (C, D))

And FYI, I would use tuples instead of lists for your points. E.g.

A = (X, Y)

EDIT: Initially there was a typo. That was fixed Sept 2014 thanks to @zidik.

This is simply the Python transliteration of the following formula, where the lines are (a1, a2) and (b1, b2) and the intersection is p. (If the denominator is zero, the lines have no unique intersection.)

2 of 13
94

Can't stand aside,

So we have linear system:

A1 * x + B1 * y = C1
A2 * x + B2 * y = C2

let's do it with Cramer's rule, so solution can be found in determinants:

x = Dx/D
y = Dy/D

where D is main determinant of the system:

A1 B1
A2 B2

and Dx and Dy can be found from matricies:

C1 B1
C2 B2

and

A1 C1
A2 C2

(notice, as C column consequently substitues the coef. columns of x and y)

So now the python, for clarity for us, to not mess things up let's do mapping between math and python. We will use array L for storing our coefs A, B, C of the line equations and intestead of pretty x, y we'll have [0], [1], but anyway. Thus, what I wrote above will have the following form further in the code:

for D

L1[0] L1[1]
L2[0] L2[1]

for Dx

L1[2] L1[1]
L2[2] L2[1]

for Dy

L1[0] L1[2]
L2[0] L2[2]

Now go for coding:

line - produces coefs A, B, C of line equation by two points provided,
intersection - finds intersection point (if any) of two lines provided by coefs.

from __future__ import division 

def line(p1, p2):
    A = (p1[1] - p2[1])
    B = (p2[0] - p1[0])
    C = (p1[0]*p2[1] - p2[0]*p1[1])
    return A, B, -C

def intersection(L1, L2):
    D  = L1[0] * L2[1] - L1[1] * L2[0]
    Dx = L1[2] * L2[1] - L1[1] * L2[2]
    Dy = L1[0] * L2[2] - L1[2] * L2[0]
    if D != 0:
        x = Dx / D
        y = Dy / D
        return x,y
    else:
        return False

Usage example:

L1 = line([0,1], [2,3])
L2 = line([2,3], [0,4])

R = intersection(L1, L2)
if R:
    print "Intersection detected:", R
else:
    print "No single intersection point detected"
🌐
Educative
educative.io › answers › what-is-the-numpyintersect1d-function-in-python
What is the numpy.intersect1d() function in Python?
Lines 17–18: We create two input arrays, e and f. Line 21: We use intersect1d() to find the intersection of e and f, and print the results. The return_indices argument in intersect1d() has been set to True. As a result, intersect1d() returns two extra arrays, which contain indices of the intersection elements in the two input arrays.
🌐
Readthedocs
scipy-cookbook.readthedocs.io › items › Intersection.html
Function intersections — SciPy Cookbook documentation
July 31, 2009 - Consider the example of finding the intersection of a polynomial and a line: $y_1=x_1^2$ $y_2=x_2+1$ In [2]: from scipy.optimize import fsolve import numpy as np def f(xy): x, y = xy z = np.array([y - x**2, y - x - 1.0]) return z fsolve(f, [1.0, 2.0]) Out[2]: array([ 1.61803399, 2.61803399]) See also: http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fsolve.html#scipy.optimize.fsolve ·
🌐
Plain English
python.plainenglish.io › how-to-find-an-intersection-between-two-matrices-easily-using-numpy-30263373b546
How to find an Intersection between two matrices easily using NumPy | by Sameer | Python in Plain English
February 18, 2021 - In Set theory, the intersection ... the set of elements contained in both A and B. Symbolically, we represent the intersection as - ... We also the above symbol as AND. Programatically this becomes very easy to code or to find the intersection between two sets. Using NumPy, we can find ...
🌐
Stack Overflow
stackoverflow.com › questions › 60411126 › intersection-points-of-two-lines-by-numpy
python - intersection points of two lines by numpy - Stack Overflow
February 26, 2020 - Note that you cannot use == to check if two float numbers are equal! ... import numpy as np a = np.random.random(20) * 2 # 20 random float numbers between 0 and 2 b = np.ones_like(a, dtype=np.float) # 20 numbers equal to 1 epsilon = 0.05 solution = np.abs(a-b) < epsilon # index of items in `a` that are close enough (epsilon) to `b` print(solution)
🌐
Rosetta Code
rosettacode.org › wiki › Find_the_intersection_of_two_lines
Find the intersection of two lines - Rosetta Code
June 9, 2026 - BEGIN # mode to hold a point # MODE POINT = STRUCT( REAL x, y ); # mode to hold a line expressed as y = mx + c # MODE LINE = STRUCT( REAL m, c ); # returns the line that passes through p1 and p2 # PROC find line = ( POINT p1, p2 )LINE: IF x OF p1 = x OF p2 THEN # the line is vertical # LINE( 0, x OF p1 ) ELSE # the line is not vertical # REAL m = ( y OF p1 - y OF p2 ) / ( x OF p1 - x OF p2 ); LINE( m, y OF p1 - ( m * x OF p1 ) ) FI # find line # ; # returns the intersection of two lines - the lines must be distinct and not parallel # PRIO INTERSECTION = 5; OP INTERSECTION = ( LINE l1, l2 )POIN
Top answer
1 of 3
8

The line through A0 and A1 has parametric equation (1-t)*A0 + t*A1, where t is the parameter. The line through B0 and B1 has parametric equation (1-s)*A0 + s*A1, where s is the parameter. Setting these equal, we get the system (A1-A0)t + (B0-B1)s == B0-A0. So, the right hand side is B0-A0 and the matrix has columns A1-A0 and B0-B1. The system can be solved with np.linalg.solve. Complete example:

A = np.array([[4, 0], [4, -3]])
B = np.array([[6, 2], [10, 2]])
t, s = np.linalg.solve(np.array([A[1]-A[0], B[0]-B[1]]).T, B[0]-A[0])
print((1-t)*A[0] + t*A[1])
print((1-s)*B[0] + s*B[1])

Both print commands output [4., 2.] confirming the correctness. (The second print it really redundant.)

2 of 3
0

Here is a function I wrote to find the closest point between two 3d lines

import scipy.optimize
#takes in two lines, the line formed by pt1 and pt2, and the line formed by pt3 and pt4, and finds their intersection or closest point
def fourptsMeetat(pt1,pt2,pt3,pt4):
    #least squares method
    def errFunc(estimates):
        s, t = estimates
        x = pt1 + s * (pt2 - pt1) - (pt3 + t * (pt4 - pt3))
        return x

    estimates = [1, 1]

    sols = scipy.optimize.least_squares(errFunc, estimates)
    s,t = sols.x

    x1 =  pt1[0] + s * (pt2[0] - pt1[0])
    x2 =  pt3[0] + t * (pt4[0] - pt3[0])
    y1 =  pt1[1] + s * (pt2[1] - pt1[1])
    y2 =  pt3[1] + t * (pt4[1] - pt3[1])
    z1 =  pt1[2] + s * (pt2[2] - pt1[2])
    z2 = pt3[2] + t * (pt4[2] - pt3[2])

    x = (x1 + x2) / 2  #halfway point if they don't match
    y = (y1 + y2) / 2  # halfway point if they don't match
    z = (z1 + z2) / 2  # halfway point if they don't match

    return (x,y,z)
🌐
GitHub
gist.github.com › kylemcdonald › 6132fc1c29fd3767691442ba4bc84018
Python Line Segment Intersection example. · GitHub
Python Line Segment Intersection example. GitHub Gist: instantly share code, notes, and snippets.
🌐
TutorialsPoint
tutorialspoint.com › how-to-find-intersection-between-two-numpy-arrays
Numpy intersect1d() Function
March 16, 2021 - numpy.intersect1d(ar1, ar2, assume_unique=False, return_indices=False) Following are the parameters of the Numpy intersect1d() function −
🌐
Harvey Mudd College
cs.hmc.edu › ACM › lectures › intersections.html
Uten tittel
# # intersections.py # # Python for finding line intersections # intended to be easily adaptable for line-segment intersections # import math def intersectLines( pt1, pt2, ptA, ptB ): """ this returns the intersection of Line(pt1,pt2) and Line(ptA,ptB) returns a tuple: (xi, yi, valid, r, s), where (xi, yi) is the intersection r is the scalar multiple such that (xi,yi) = pt1 + r*(pt2-pt1) s is the scalar multiple such that (xi,yi) = pt1 + s*(ptB-ptA) valid == 0 if there are 0 or inf. intersections (invalid) valid == 1 if it has a unique intersection ON the segment """ DET_TOLERANCE = 0.00000001