确定线段是否与多边形相交 [英] Determine if a line segment intersects a polygon

查看:393
本文介绍了确定线段是否与多边形相交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在2D平面上有一个矢量(由2个点组成的线),如何确定它是否已通过多边形?

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?

我已经阅读了这篇文章如何确定2D点是否在其中一个多边形?这给了我一些想法,以了解该点是否在多边形内,但是我需要查看它是否已通过/相交.

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.

推荐答案

如果您要使用Python库进行几何运算,请查看 shapely .它使它像someline.intersects(somepolygon)一样简单.

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()

这将产生:

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

这篇关于确定线段是否与多边形相交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆