Code Example: line_intersection.py

#!/usr/bin/python3
# ===================================================================
# return the intersection point of two lines
# given line segment a defined by endpoints a1, a2
# given line segment b defined by endpoints b1, b2
# -------------------------------------------------------------------
# line segment intersection using vectors
# see Computer Graphics by F.S. Hill
# ===================================================================

import numpy as np

def perp(a):
    b = np.empty_like(a)
    b[0] = -a[1]
    b[1] = a[0]
    return b

# -------------------------------------------------------------------
# calculate intersection point using vectors
# -------------------------------------------------------------------

def intersection_point(a1,a2,b1,b2):
    da = a2-a1
    db = b2-b1
    dp = a1-b1
    dap = perp(da)
    denom = np.dot(dap,db)
    num = np.dot(dap,dp)
    return (num/denom)*db + b1