Check if two lines (each with start-end positions) overlap in python - python

I have the following two sets of position each correspond to the start and end position:
line T: t1-t2 (t1 = start_pos, t2 = end_pos)
line S: s1-s2 (s1 = start_pos, t2 = end_pos)
I want to write the algorithm in Python to check if T intersect with S.
Example 1:
t1-t2=55-122 and s1-s2=58-97
s1------------s2
t1-----------------t2
This should return True
Example 2:
t1-t2=4-66 / t1-t2=143-166 and s1-s2=80-141
s1----s2
t1--t2 t1---t2
Both instances of T should return False
But why this code failed:
def is_overlap(pos, dompos):
"""docstring for is_overlap"""
t1,t2 = [int(x) for x in pos.split("-")]
s1,s2 = [int(x) for x in dompos.split("-")]
# Here we define the instance of overlapness
if (t1 >= s1 and t2 >= s2) or \
(t1 >= s1 and t2 <= s2) or \
(t1 <= s1 and t2 >= s2) or \
(t1 <= s1 and t2 <= s2):
return True
else:
return False
which output this:
In [2]: is_overlap('55-122', '58-97')
Out[2]: True
In [3]: is_overlap('4-66', '80-141')
Out[3]: True
In [4]: is_overlap('143-166', '80-141')
Out[4]: True
What's the right way to do it?

Consider a span [a, b] and another span [x, y]. They either overlap or they are separate.
If they are separate, one of two things must be true:
[a, b] is to the left of [x, y], or
[x, y] is to the left of [a, b].
If [a, b] is to the left of [x, y], we have b < x.
If [x, y] is to the left of [a, b], we have y < a.
If neither of these is true, the spans cannot be separate. They must overlap.
This logic is implemented in the following function.
def are_separate(r, s): # r and s are ordered pairs
(a, b) = r
(x, y) = s
if b < x or y < a:
return True
else:
return False
More concisely:
def are_separate(r, s):
(a, b) = r
(x, y) = s
return b < x or y < a
Even more concisely:
def are_separate(r, s):
return r[1] < s[0] or s[1] < r[0]
If you want the contrary function, are_overlapping, just negate the expression:
def are_overlapping(r, s):
return not(r[1] < s[0] or s[1] < r[0])
Which is logically equivalent to:
def are_overlapping(r, s):
return r[1] >= s[0] and s[1] >= r[0]

Your conditions are wrong; check them again. For instance, the first condition implies that (t_1, t_2) = (100, 200) and (s_1, s_2) = (50, 60) to be a valid set of overlapping lines. But clearly, they aren't.
Something else you might want to consider is if the user inputs the coordinates in backwards. What if he puts in something like '80-30'?

For those who want two lines in two dimensions, #michael's answer is not enough. The following code is based on the equation found in the Wikipedia page listed just above the code as well as a little Pythagoras to check the intersection lies between the appropriate points. https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
x1, y1, x2, y2 = 200, 200, 300, 300
x3, y3, x4, y4 = 200, 150, 300, 350
px = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / \
((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4))
py = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)) / \
((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4))
if ((x1 - px) ** 2 + (y1 - py) ** 2) ** 0.5 + ((x2 - px) ** 2 + (y2 - py) ** 2) ** 0.5 == \
((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 and \
((x3 - px) ** 2 + (y3 - py) ** 2) ** 0.5 + ((x4 - px) ** 2 + (y4 - py) ** 2) ** 0.5 == \
((x3 - x4) ** 2 + (y3 - y4) ** 2) ** 0.5:
print("Overlap at point: (%s, %s)" % (px, py))
else:
print("No overlap.")

Related

Middlepoint on circle between 2 points

I'm trying to find middlepoint on the circle between 2 points, pictorial drawing
There are given radius, p1, p2 and middle of the circle.
Distance betweeen p1 and p2 is an diameter, and I'm trying to make up python formula that returns point on the circle between those 2 points. I know this is rather silly question but I'm trying to make this for 3 hours now and all I can find on web is distance between those 2 points.
I'm trying to find formula for p3 (like in the picture)
That's what I ended up making so far:
import math
points = [[100, 200], [250, 350]]
midpoint = (int(((points[0][0] + points[1][0]) / 2)), int(((points[0][1] + points[1][1]) / 2)))
radius = int(math.sqrt(((points[1][0] - points[0][0])**2) + ((points[1][1] - points[0][1])**2))) // 2
# This below is wrong
print(int(midpoint[0] - math.sqrt((points[0][1] - midpoint[1]) ** 2)),
int(midpoint[1] - math.sqrt((points[0][0] - midpoint[1]) ** 2)))
There is no need for trigonometry, which is total overkill.
The center of the circle is Xs= (X1 + X2) / 2, Ys= (Y1 + Y2) / 2.
The two opposite "middlepoints" are given by X3 = Xs - (Y1 - Ys), Y3 = Ys + (X1 - Xs) and X4 = Xs + (Y1 - Ys), Y4 = Ys - (X1 - Xs).
If you prefer direct formulas, X3 = (X1 + X2 - Y1 + Y2) / 2, Y3 = (X1 - X2 + Y1 + Y2) / 2...
To generate points on the circle use polar equation (https://math.stackexchange.com/questions/154550/polar-equation-of-a-circle)
import math
import random
points = [[100, 200], [250, 350]]
midpoint = (int(((points[0][0] + points[1][0]) / 2)), int(((points[0][1] + points[1][1]) / 2)))
radius = int(math.sqrt(((points[1][0] - points[0][0])**2) + ((points[1][1] - points[0][1])**2))) // 2
angle = random.uniform(0, 2 * math.pi)
x_relative = radius * math.cos(angle)
y_relative = radius * math.sin(angle)
x = midpoint[0] + x_relative
y = midpoint[1] + y_relative
print(f"{x} {y}")
To find middle point on the circle between points:
import math
points = [[100, 200], [250, 350]]
midpoint = (int(((points[0][0] + points[1][0]) / 2)), int(((points[0][1] + points[1][1]) / 2)))
radius = int(math.sqrt(((points[1][0] - points[0][0])**2) + ((points[1][1] - points[0][1])**2))) // 2
points_relative = [[points[0][0] - midpoint[0], points[0][1] - midpoint[1]], [points[1][0] - midpoint[0], points[1][1] - midpoint[1]]]
midpoint_points_relative = [[points_relative[0][1], - points_relative[0][0]], [points_relative[1][1], - points_relative[1][0]]]
midpoint_points = [[midpoint_points_relative[0][0] + midpoint[0], midpoint_points_relative[0][1] + midpoint[1]], [midpoint_points_relative[1][0] + midpoint[0], midpoint_points_relative[1][1] + midpoint[1]]]
print(points)
print(midpoint)
print(points_relative)
print(midpoint_points)
You can use this page to test results: https://www.desmos.com/calculator/mhq4hsncnh

Implementing a numerical integration method in Python

I am trying to write a numerical integral calculator as my first Python project. The method takes a starting x value, a delta x value, and a set of y values and returns a lower and an upper bound. I am expecting the result of the numerical integration to converge as dx gets smaller, but it is getting larger.
I am trying to integrate an exponential from 0 to 1 and get the result to converge to 1/3 as dx gets smaller. Currently a dx of 0.1 gives me bounds of (0.14000000000000004, 0.17200000000000004). A dx of 0.01 has bounds of (0.30894500000000014, 0.313747).
Here is my code:
class Linear:
"""Creates a linear function from 2 points"""
def __init__(self, x0, y0, x1, y1):
self.__x0 = x0
self.__y0 = y0
self.__x1 = x1
self.__y1 = y1
self.__a = ((y1 - y0) / (x1 - x0))
self.__b = y0 - (self.__a * x0)
def fun(self, x):
return self.__a * x + self.__b
def integrate(x0, dx, data):
if len(data) < 3:
raise ValueError("data passed to integrate doesn't have enough data")
else:
i, lb, ub = 2, 0, 0
while i < len(data):
y0, y1, y2 = data[i - 2], data[i - 1], data[i]
lin = Linear(x0, y0, x0 + dx + dx, y2)
lin_delta = lin.fun(x0 + dx)
if y1 < lin_delta:
if y0 < y1:
lb += (y0 * dx)
ub += ((((y1 - y0) * dx) / 2) + (y0 * dx))
else:
lb += (y1 * dx)
ub += ((((y0 - y1) * dx) / 2) + (y1 * dx))
else:
if y0 < y1:
ub += (y1 * dx)
lb += ((((y1 - y0) * dx) / 2) + (y0 * dx))
else:
ub += (y0 * dx)
lb += ((((y0 - y1) * dx) / 2) + (y1 * dx))
i += 1
x0 += dx
return lb, ub
if __name__ == '__main__':
j = 0
d = []
dxj = 0.1
while j < (1/dxj):
d += [(j * dxj) * (j * dxj)]
j += 1
print(d)
print(integrate(0, dxj, d))
Also, what is the best way to avoid name collisions with counters like i?

In python how to get intersection point of three or more circles with or without error

Given three circles as
(x - x1)**2 + (y - y1)**2 = r1**2
(x - x2)**2 + (y - y2)**2 = r2**2
(x - x3)**2 + (y - y3)**2 = r3**2
How do I find in python the (x,y) point of intersection of the three circles? More precisely, how can this be robust even when the three circles do not intersect exactly in one point but none?
I have tried by using least_squares from scipy but I am not sure it's working properly since even when the circles actually intercept in one point, it gives another result.
def intersectionPoint(p1,p2,p3):
x1, y1, dist_1 = (p1[0], p1[1], p1[2])
x2, y2, dist_2 = (p2[0], p2[1], p2[2])
x3, y3, dist_3 = (p3[0], p3[1], p3[2])
def eq(g):
x, y, r = g
return (
(x - x1)**2 + (y - y1)**2 - (dist_1 - r )**2,
(x - x2)**2 + (y - y2)**2 - (dist_2 - r )**2,
(x - x3)**2 + (y - y3)**2 - (dist_3 - r )**2)
guess = (100, 100, 0)
ans = scipy.optimize.least_squares(eq, guess)
return ans
ans = intersectionPoint((0,0,9962),(7228,0,9784),(4463,3109,6251))
Whilst using least_squares to solve this problem is possible, there are a few things that need changing in the code.
The eq function should only take a point (x,y) as a parameter since you are looking for the intersection point.
The return value should be (x - x1)**2 + (y - y1)**2 - dist_1**2 for each circle (that's the square of the distance to the circle).
The call to least_squares should be done with some additional parameters to avoid false positives, namely ftol=None, xtol=None. Please refer to the docs to understand the role of these parameters. They avoid termination by the change of the cost function and the change of the independent variables.
I would change the guess to a point on the first circle, so that the algorithm starts in a relevant region, guess = (x1, y1 + dist_1)
Of course, don't forget to check the success attribute to check whether the algorithm converged!
The code then becomes:
from scipy.optimize import least_squares
def intersectionPoint(p1,p2,p3):
x1, y1, dist_1 = (p1[0], p1[1], p1[2])
x2, y2, dist_2 = (p2[0], p2[1], p2[2])
x3, y3, dist_3 = (p3[0], p3[1], p3[2])
def eq(g):
x, y = g
return (
(x - x1)**2 + (y - y1)**2 - dist_1**2,
(x - x2)**2 + (y - y2)**2 - dist_2**2,
(x - x3)**2 + (y - y3)**2 - dist_3**2)
guess = (x1, y1 + dist_1)
ans = least_squares(eq, guess, ftol=None, xtol=None)
return ans
ans = intersectionPoint((0,0,1),(2,0,1),(1,-1,1))

python: interpolation: finding a rectangle that minimally include a point

I am implementing a bilinear interpolation as in How to perform bilinear interpolation in Python
I have a sorted list of points that are the vertexes of my regular grid.
[[x1,y1,z1],[x2,y2,z2],[x3,y3,z3],[x4,y4,z4],[x5,y5,z5],...]
I want to interpolate linearly on the point (x,y). I have written the following code
def f(x, y, points):
for i in range(len(points)-1, -1, -1):
if (x>points[i][0])and(y>points[i][1]):
break
try:
pp = [points[i], points[i+1]]
except IndexError:
pp = [points[i], points[i-1]]
for j in range(len(points)):
if (x<points[j][0])and(y<points[j][1]):
break
pp.append(points[j-1])
pp.append(points[j])
(x1, y1, q11), (_x1, y2, q12), (x2, _y1, q21), (_x2, _y2, q22) = pp
return (q11 * (x2 - x) * (y2 - y) +
q21 * (x - x1) * (y2 - y) +
q12 * (x2 - x) * (y - y1) +
q22 * (x - x1) * (y - y1)) / ((x2 - x1) * (y2 - y1))
but this code doesn't work on the boundaries. I would think this is common problem in interpolation, so I was wondering how I should select the smallest rectangle of points around (x,y) from my regular grid.
Your grid is regular, so you don't need to traverse all points to determine cell indexes. Just divide coordinates by cell size and round result to smaller integer. 1D example: if first point has coordinate 1 and cell size is 2, point 6 lies at int (6-1)/2 = 2-nd interval
Restrict result index to ensure that it is in grid limits - so points outside grid will use border cells
i = int((x - points[i][0]) / xsize) #not sure what is the best way in Python
if (i < 0):
i = 0
if (i >= XCount):
i = XCount - 1
// same for j and y-coordinate
Following the suggestions in the comments I have written the following code:
def f(x, y, points):
points = sorted(points)
xunique = np.unique([point[0] for point in points])
yunique = np.unique([point[1] for point in points])
xmax = np.max(xunique)
ymax = np.max(yunique)
deltax = xunique[1] - xunique[0]
deltay = yunique[1] - yunique[0]
x0 = xunique[0]
y0 = yunique[0]
ni = len(xunique)
nj = len(yunique)
i1 = int(np.floor((x-x0)/deltax))
if i1 == ni:
i1 = i1 - 1
i2 = int(np.ceil((x-x0)/deltax))
if i2 == ni:
i2 = i2 - 1
j1 = int(np.floor((y-y0)/deltay))
if j1 == nj:
j1 = j1 - 1
j2 = int(np.ceil((y-y0)/deltay))
if j2 == ni:
j2 = j2 - 1
pp=[]
if (i1==i2):
if i1>0:
i1=i1-1
else:
i2=i2+1
if (j1==j2):
if j1>0:
j1=j1-1
else:
j2=j2+1
pp=[points[i1 * nj + j1], points[i1 * nj + j2],
points[i2 * nj + j1], points[i2 * nj + j2]]
(x1, y1, q11), (_x1, y2, q12), (x2, _y1, q21), (_x2, _y2, q22) = pp
return (q11 * (x2 - x) * (y2 - y) +
q21 * (x - x1) * (y2 - y) +
q12 * (x2 - x) * (y - y1) +
q22 * (x - x1) * (y - y1)) / ((x2 - x1) * (y2 - y1))

How do I compute the intersection point of two lines?

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 2
C = [X, Y]
D = [X, Y]
# Compute this:
point_of_intersection = [X, Y]
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.)
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"
Here is a solution using the Shapely library. Shapely is often used for GIS work, but is built to be useful for computational geometry. I changed your inputs from lists to tuples.
Problem
# Given these endpoints
#line 1
A = (X, Y)
B = (X, Y)
#line 2
C = (X, Y)
D = (X, Y)
# Compute this:
point_of_intersection = (X, Y)
Solution
import shapely
from shapely.geometry import LineString, Point
line1 = LineString([A, B])
line2 = LineString([C, D])
int_pt = line1.intersection(line2)
point_of_intersection = int_pt.x, int_pt.y
print(point_of_intersection)
Using formula from:
https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
def findIntersection(x1,y1,x2,y2,x3,y3,x4,y4):
px= ( (x1*y2-y1*x2)*(x3-x4)-(x1-x2)*(x3*y4-y3*x4) ) / ( (x1-x2)*(y3-y4)-(y1-y2)*(x3-x4) )
py= ( (x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4) ) / ( (x1-x2)*(y3-y4)-(y1-y2)*(x3-x4) )
return [px, py]
If your lines are multiple points instead, you can use this version.
import numpy as np
import matplotlib.pyplot as plt
"""
Sukhbinder
5 April 2017
Based on:
"""
def _rect_inter_inner(x1,x2):
n1=x1.shape[0]-1
n2=x2.shape[0]-1
X1=np.c_[x1[:-1],x1[1:]]
X2=np.c_[x2[:-1],x2[1:]]
S1=np.tile(X1.min(axis=1),(n2,1)).T
S2=np.tile(X2.max(axis=1),(n1,1))
S3=np.tile(X1.max(axis=1),(n2,1)).T
S4=np.tile(X2.min(axis=1),(n1,1))
return S1,S2,S3,S4
def _rectangle_intersection_(x1,y1,x2,y2):
S1,S2,S3,S4=_rect_inter_inner(x1,x2)
S5,S6,S7,S8=_rect_inter_inner(y1,y2)
C1=np.less_equal(S1,S2)
C2=np.greater_equal(S3,S4)
C3=np.less_equal(S5,S6)
C4=np.greater_equal(S7,S8)
ii,jj=np.nonzero(C1 & C2 & C3 & C4)
return ii,jj
def intersection(x1,y1,x2,y2):
"""
INTERSECTIONS Intersections of curves.
Computes the (x,y) locations where two curves intersect. The curves
can be broken with NaNs or have vertical segments.
usage:
x,y=intersection(x1,y1,x2,y2)
Example:
a, b = 1, 2
phi = np.linspace(3, 10, 100)
x1 = a*phi - b*np.sin(phi)
y1 = a - b*np.cos(phi)
x2=phi
y2=np.sin(phi)+2
x,y=intersection(x1,y1,x2,y2)
plt.plot(x1,y1,c='r')
plt.plot(x2,y2,c='g')
plt.plot(x,y,'*k')
plt.show()
"""
ii,jj=_rectangle_intersection_(x1,y1,x2,y2)
n=len(ii)
dxy1=np.diff(np.c_[x1,y1],axis=0)
dxy2=np.diff(np.c_[x2,y2],axis=0)
T=np.zeros((4,n))
AA=np.zeros((4,4,n))
AA[0:2,2,:]=-1
AA[2:4,3,:]=-1
AA[0::2,0,:]=dxy1[ii,:].T
AA[1::2,1,:]=dxy2[jj,:].T
BB=np.zeros((4,n))
BB[0,:]=-x1[ii].ravel()
BB[1,:]=-x2[jj].ravel()
BB[2,:]=-y1[ii].ravel()
BB[3,:]=-y2[jj].ravel()
for i in range(n):
try:
T[:,i]=np.linalg.solve(AA[:,:,i],BB[:,i])
except:
T[:,i]=np.NaN
in_range= (T[0,:] >=0) & (T[1,:] >=0) & (T[0,:] <=1) & (T[1,:] <=1)
xy0=T[2:,in_range]
xy0=xy0.T
return xy0[:,0],xy0[:,1]
if __name__ == '__main__':
# a piece of a prolate cycloid, and am going to find
a, b = 1, 2
phi = np.linspace(3, 10, 100)
x1 = a*phi - b*np.sin(phi)
y1 = a - b*np.cos(phi)
x2=phi
y2=np.sin(phi)+2
x,y=intersection(x1,y1,x2,y2)
plt.plot(x1,y1,c='r')
plt.plot(x2,y2,c='g')
plt.plot(x,y,'*k')
plt.show()
I didn't find an intuitive explanation on the web, so now that I worked it out, here's my solution. This is for infinite lines (what I needed), not segments.
Some terms you might remember:
A line is defined as y = mx + b OR y = slope * x + y-intercept
Slope = rise over run = dy / dx = height / distance
Y-intercept is where the line crosses the Y axis, where X = 0
Given those definitions, here are some functions:
def slope(P1, P2):
# dy/dx
# (y2 - y1) / (x2 - x1)
return(P2[1] - P1[1]) / (P2[0] - P1[0])
def y_intercept(P1, slope):
# y = mx + b
# b = y - mx
# b = P1[1] - slope * P1[0]
return P1[1] - slope * P1[0]
def line_intersect(m1, b1, m2, b2):
if m1 == m2:
print ("These lines are parallel!!!")
return None
# y = mx + b
# Set both lines equal to find the intersection point in the x direction
# m1 * x + b1 = m2 * x + b2
# m1 * x - m2 * x = b2 - b1
# x * (m1 - m2) = b2 - b1
# x = (b2 - b1) / (m1 - m2)
x = (b2 - b1) / (m1 - m2)
# Now solve for y -- use either line, because they are equal here
# y = mx + b
y = m1 * x + b1
return x,y
Here's a simple test between two (infinite) lines:
A1 = [1,1]
A2 = [3,3]
B1 = [1,3]
B2 = [3,1]
slope_A = slope(A1, A2)
slope_B = slope(B1, B2)
y_int_A = y_intercept(A1, slope_A)
y_int_B = y_intercept(B1, slope_B)
print(line_intersect(slope_A, y_int_A, slope_B, y_int_B))
Output:
(2.0, 2.0)
The most concise solution I have found uses Sympy: https://www.geeksforgeeks.org/python-sympy-line-intersection-method/
# import sympy and Point, Line
from sympy import Point, Line
p1, p2, p3 = Point(0, 0), Point(1, 1), Point(7, 7)
l1 = Line(p1, p2)
# using intersection() method
showIntersection = l1.intersection(p3)
print(showIntersection)
With the scikit-spatial library you can easily do it in the following way:
import matplotlib.pyplot as plt
from skspatial.objects import Line
# Define the two lines.
line_1 = Line.from_points([3, -2], [5, 4])
line_2 = Line.from_points([-1, 0], [3, 2])
# Compute the intersection point
intersection_point = line_1.intersect_line(line_2)
# Plot
_, ax = plt.subplots()
line_1.plot_2d(ax, t_1=-2, t_2=3, c="k")
line_2.plot_2d(ax, t_1=-2, t_2=3, c="k")
intersection_point.plot_2d(ax, c="r", s=100)
grid = ax.grid()
there is already an answer that uses formula from Wikipedia but that doesn't have any check point to check if line segments actually intersect so here you go
def line_intersection(a, b, c, d):
t = ((a[0] - c[0]) * (c[1] - d[1]) - (a[1] - c[1]) * (c[0] - d[0])) / ((a[0] - b[0]) * (c[1] - d[1]) - (a[1] - b[1]) * (c[0] - d[0]))
u = ((a[0] - c[0]) * (a[1] - b[1]) - (a[1] - c[1]) * (a[0] - b[0])) / ((a[0] - b[0]) * (c[1] - d[1]) - (a[1] - b[1]) * (c[0] - d[0]))
# check if line actually intersect
if (0 <= t and t <= 1 and 0 <= u and u <= 1):
return [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])]
else:
return False
#usage
print(line_intersection([0,0], [10, 10], [0, 10], [10,0]))
#result [5.0, 5.0]
img And You can use this kode
class Nokta:
def __init__(self,x,y):
self.x=x
self.y=y
class Dogru:
def __init__(self,a,b):
self.a=a
self.b=b
def Kesisim(self,Dogru_b):
x1= self.a.x
x2=self.b.x
x3=Dogru_b.a.x
x4=Dogru_b.b.x
y1= self.a.y
y2=self.b.y
y3=Dogru_b.a.y
y4=Dogru_b.b.y
#Notlardaki denklemleri kullandım
pay1=((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3))
pay2=((x2-x1) * (y1 - y3) - (y2 - y1) * (x1 - x3))
payda=((y4 - y3) *(x2-x1)-(x4 - x3)*(y2 - y1))
if pay1==0 and pay2==0 and payda==0:
print("DOĞRULAR BİRBİRİNE ÇAKIŞIKTIR")
elif payda==0:
print("DOĞRULAR BİRBİRNE PARALELDİR")
else:
ua=pay1/payda if payda else 0
ub=pay2/payda if payda else 0
#x ve y buldum
x=x1+ua*(x2-x1)
y=y1+ua*(y2-y1)
print("DOĞRULAR {},{} NOKTASINDA KESİŞTİ".format(x,y))

Categories