Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a line segment intersects a polygon

If I have a vector (a line consisting of 2 points) on a 2D plane how can I determine if it has passed through a polygon?

I know I can take each line which makes up the polygon and see if any intersect but is there a better way?

I've read this one post How can I determine whether a 2D Point is within a Polygon? which gives me some ideas for seeing whether the point is within a polygon but I need to see if it has passed over/intersected it.

like image 385
David Bramer Avatar asked May 18 '11 20:05

David Bramer


1 Answers

If you want a python library for geometric operations, have a look at shapely. It makes this as simple as someline.intersects(somepolygon).

Here's a quick example of intersections, buffer, and clipping (with a nice plot... I'm using descartes to easily convert shapely polygons into matplotlib patches.).

import numpy as np
import matplotlib.pyplot as plt
import shapely.geometry
import descartes

circle = shapely.geometry.Point(5.0, 0.0).buffer(10.0)
clip_poly = shapely.geometry.Polygon([[-9.5, -2], [2, 2], [3, 4], [-1, 3]])
clipped_shape = circle.difference(clip_poly)

line = shapely.geometry.LineString([[-10, -5], [15, 5]])
line2 = shapely.geometry.LineString([[-10, -5], [-5, 0], [2, 3]])

print 'Blue line intersects clipped shape:', line.intersects(clipped_shape)
print 'Green line intersects clipped shape:', line2.intersects(clipped_shape)

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(*np.array(line).T, color='blue', linewidth=3, solid_capstyle='round')
ax.plot(*np.array(line2).T, color='green', linewidth=3, solid_capstyle='round')
ax.add_patch(descartes.PolygonPatch(clipped_shape, fc='blue', alpha=0.5))
ax.axis('equal')

plt.show()

This yields:

Blue line intersects clipped shape: True
Green line intersects clipped shape: False

enter image description here

like image 55
Joe Kington Avatar answered Sep 28 '22 06:09

Joe Kington