2

Consider there are two lines, l1, l2 and they might be intersecting or non-intersecting. Is there any elegent way to find a angle between them? Thank you

import numpy as np
from shapely import LineString

l1 = [(0,0), (1,1)]
l2 = [(0.5, 1), (0.5, 2)]

ls1 = LineString(l1)
ls2 = LineString(l2)

angle = compute_angle(ls1, ls2)

# This is I want to avoid because I have very big dataset and performance will degrade
def compute_anlge(l1, l2):
   #Extend line1 and line2 in both direction util they intersect

   # Find intersection point

   # Create new lines with the intersection point

   # find angle and return
Oli
  • 1,313
  • 14
  • 31
  • Possible duplicate of [Calculating the angle between two lines in an image in Python](https://stackoverflow.com/questions/46357099/calculating-the-angle-between-two-lines-in-an-image-in-python) – parthagar Sep 26 '18 at 11:47
  • 5
    Possible duplicate of [Finding Signed Angle Between Vectors](https://stackoverflow.com/questions/2150050/finding-signed-angle-between-vectors) –  Sep 26 '18 at 11:48
  • in math, you can find the angle between two *vectors* representing the lines, whether the lines are crossing or not is rrelevant for this calculation. (see the duplicate target from JETM) – Pac0 Sep 26 '18 at 11:56

2 Answers2

2

First, find the angle for each segment by moving it to the origin:

seg = np.array(l2)
seg = seg[1] - seg[0]

Then, use np.angle

 angle_l2 = np.angle(complex(*(seg)), deg=True)

Then, you can simply calculate the difference between the angles.

Andy
  • 450
  • 2
  • 8
  • 1
    A parenthesis is missing in your answer. The last line should look like this: angle_2 = np.angle(complex(*(seg)), deg=True) – Jonas Frei May 16 '22 at 12:36
1

Using the slopes of two lines, you can just get the arc tangents to find their respective angles with respect to origin. Then, get the positive difference of two angles. All done!

import math
from math import pi as PI

l1 = [(0,0), (1,1)]
l2 = [(0.5, 1), (0.5, 2)]
m1 = (l1[1][1]-l1[0][1])/(l1[1][0]-l1[0][0])
m2 = (l2[1][1]-l2[0][1])/(l2[1][0]-l2[0][0])

angle_rad = abs(math.atan(m1) - math.atan(m2))
angle_deg = angle_rad*180/PI

There, with both radian and degree values.

Seraph Wedd
  • 864
  • 6
  • 14