Intersection of segment with polygon

2019-07-24 16:12发布

问题:

I have to create a function in MATLAB that performs the following task:

Input:

p polygon in the form

p = [x1,y1; x2,y2; x3,y3; x4,y4...]

s struct with the segment from A to B

s = struct('A',[x,y],'B'[u,w])

Return:

1) An integer indicating how many intersections there are between the segment and the polygon (e.g., 0,1,2)

2) A new segment from A to B, where A is the first intersection or the initial point of the input segment and B the second point of the intersection or the last point of the segment input.

I have an idea on how to do it by using the function inpolygon. I have been reading how to use this function, and know that to use that, I should provide a query point and the coordinates of the polygon vertices. It will return 1 or 0 depending on whether it is inside or not.

My question is, how can I get the query point of the segment that is placed exactly in the boundary (in the case that the segment intersects with it)?

回答1:

If you have the Mapping Toolbox installed, you could use polyxpoly. As this is a rather basic problem, there are quite a few free MATLAB-codes out there on the File Exchange. Here is what I found for the search term 'polygon intersect':

  • 2D Polygon edges intersection by Bruno Luong

    Find the intersection points of the edges of two 2D polygons, a simple function made to follow up a Newsgroup discussion

  • Curve Intersect 2 by Sebastian Hölz

    This file is based on the Curve Intersect function by Duane Hanselman. It extends the scope of the function to handle arbitrary lines / polygons, which may also have vertical segments or segments with non-increasing x-values.

  • Curve intersections by NS

    While a few other functions already exist in FEX that compute the intersection points of curves, this short piece of code was written with speed being the highest priority. No loops are used throughout, taking full advantage of MATLAB's vectorization capabilities

  • Fast and Robust Curve Intersections by Douglas Schwarz

    This function computes the (x,y) locations where two curves intersect. The curves can be broken with NaNs or have vertical segments. It is also very fast (at least on data that represents what I think is a typical application).

  • geom2d by David Legland

    [...] derive new shapes: intersection between 2 lines, between a line and a circle, parallel and perpendicular lines