Created
August 20, 2022 15:35
-
-
Save shionryuu/196f6a5477332d30b9d18ecb08558ab0 to your computer and use it in GitHub Desktop.
Check if two line segments intersect
This file contains 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.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# | |
# Notes on intersection: | |
# | |
# https://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/ | |
# | |
# https://stackoverflow.com/questions/3838329/how-can-i-check-if-two-segments-intersect | |
# | |
# Permalink: | |
# | |
# https://stackoverflow.com/a/61699051 | |
# | |
from shapely.geometry import LineString | |
class Point: | |
def __init__(self,x,y): | |
self.x = x | |
self.y = y | |
def ccw(A,B,C): | |
return (C.y-A.y)*(B.x-A.x) > (B.y-A.y)*(C.x-A.x) | |
def intersect(A,B,C,D): | |
return ccw(A,C,D) != ccw(B,C,D) and ccw(A,B,C) != ccw(A,B,D) | |
def ShapelyIntersect(A,B,C,D): | |
return LineString([(A.x,A.y),(B.x,B.y)]).intersects(LineString([(C.x,C.y),(D.x,D.y)])) | |
a = Point(0,0) | |
b = Point(0,1) | |
c = Point(1,1) | |
d = Point(1,0) | |
''' | |
Test points: | |
b(0,1) c(1,1) | |
a(0,0) d(1,0) | |
''' | |
# F | |
print(intersect(a,b,c,d)) | |
# T | |
print(intersect(a,c,b,d)) | |
print(intersect(b,d,a,c)) | |
print(intersect(d,b,a,c)) | |
# F | |
print(intersect(a,d,b,c)) | |
# same end point cases: | |
print("same end points") | |
# F - not intersected | |
print(intersect(a,b,a,d)) | |
# T - This shows as intersected | |
print(intersect(b,a,a,d)) | |
# F - this does not | |
print(intersect(b,a,d,a)) | |
# F - this does not | |
print(intersect(a,b,d,a)) | |
print("same end points, using shapely") | |
# T | |
print(ShapelyIntersect(a,b,a,d)) | |
# T | |
print(ShapelyIntersect(b,a,a,d)) | |
# T | |
print(ShapelyIntersect(b,a,d,a)) | |
# T | |
print(ShapelyIntersect(a,b,d,a)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How can I check if two segments intersect?