Intersection of two line segments in Python

Question:

Different articles have discussed about the intersection of two line segments in Python such as

How do I compute the intersection point of two lines?,

Numpy and line intersections,

How can I check if two segments intersect?

But, no one made it perfect since, they did not cover an especial case. Given the following two line segments:

a = [(0, 2), (2, 4)]
b = [(-2, 0), (0, 2)]

These two segment lines have the same slope. In fact, they intersect at (0, 2). How can we obtain such the intersection point?

The second part of my question, what if two line segments overlap (partially/totally)? That is,

a = [(0, 2), (2, 4)]
b = [(-2, 0), (1, 3)]
Asked By: Javad.Rad

||

Answers:

In your last reference, the first answer returns False if A1 == A2 due to the fact the lines are parallel. You present a legitimate edge case, so all you need to do in case the lines are parallel is to also check if they both lie on the same line. This is by checking if b1 == b2. Only if this condition is False, return False as the segments are parallel but do not lie on the same hyperplane. Otherwise, continue as the answer specifies, this is by checking if both segments has a common point.

Answered By: ronpi

The specification "Intersection of 2 Line Segments in 2D?" as a COMPUTATIONAL problem is quite incomplete.

What’s mainly missing is specification of the input cases, and how you want them reported in the result:

  1. A degenerate LineSeg given as input

  2. No intersection points

  3. Infinite number of intersection points

    a) LS1 and LS2 are identical (see below)

    b) LS1 and LS2 overlap by more than 1 point

  4. LS1 and LS2 share a common endPt

  5. Single intersection point i distinct from any endPt

Additionally, you need to define how much finite-precision arithmetic error will be tolerated in computing two proximate points p1 and p2 as close enough to be considered identical (epsilon), a key detail needed to fully specify cases 0, 2, 3 and 4.

Answered By: pbierre