Determine if a line segment intersects a polygon

2024/10/12 8:22:02

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.

Answer

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 descartescircle = 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

https://en.xdnf.cn/q/69677.html

Related Q&A

How to send a value from Arduino to Python and then use that value

I am in the process of building a robot that is remote controlled using Python to send control messages via the Internet through a simple GUI.I have gotten part of my code working pretty well, the GUI …

recaptcha wasnt solving by anticaptcha plugin in selenium python

Ive recently started using selenium for a project Ive been working on for a while that involves automation. One of the roadblocks in the plan was the ReCaptcha system, so I decided to use anti-captcha …

Python - check for class existance

Is there a way to check if a class has been defined/exists? I have different options on a menu, and some of them require inherited variables, so if you try to select that function before you have set …

getting a matplotlib colorbar tick outside data limits for use with boundaries keyword

I am trying to use a colorbar to label discrete, coded values plotted using imshow. I can achieve the colorbar that I want using the boundaries and values keywords, which makes the maximum value of the…

Apache Airflow - customize logging format

Is it possible to customize the format that Airflow uses for logging?I tried adding a LOG_FORMAT variable in $AIRFLOW_HOME/airflow.cfg, but it doesnt seem to take effectLOG_FORMAT = "%(asctime)s …

How can I set up Celery to call a custom worker initialization?

I am quite new to Celery and I have been trying to setup a project with 2 separate queues (one to calculate and the other to execute). So far, so good. My problem is that the workers in the execute que…

Why does print(__name__) give builtins?

Im using pycharm.2017.1.2. I installed anaconda2 with py3 environment. in Pycharm, Im using Python3 interpreter, and the code is simply:print(__name__)In Python console in Pycharm, it prints builtins.I…

List Comprehensions and Conditions?

I am trying to see if I can make this code better using list comprehensions. Lets say that I have the following lists:a_list = [HELLO,FOO,FO1BAR,ROOBAR,SHOEBAR]regex_list = [lambda x: re.search(rFOO,…

Python in operator time complexity on range()

I have the following function:def foo(length, num):return num in range(length)Whats the time complexity of this function? Noting that range() creates a Range object on Python 3, will the time complexi…

Pandas read data from a secure FTP server in Python 3

I am looking for a neat solution to read data (using either read_csv or read_sas) to a Pandas Dataframe from a secure FTP server in Python 3. All the examples I can find are many lines and some for Pyt…