Most efficient way to randomly select point within polygon?

Question:

I’m extremely new to Python and trying to figure out the most efficient way to randomly select a point within a polygon. The image I attached is representative of the scenario – my first attempt took nearly 30 seconds to generate a list of all pixel (x,y) coordinates contained in the gray area (I think I used matplotlib).

enter image description here

Based on other similar questions and suggestions I saw here, I am currently generating a rough bounding box of the polygon, setting min(x) and min(y) values based on the bounding box, and running a series of checks to see if I’ve landed in a valid area. Should I bother trying to generate a precise valid point list or is "dump and test" going to be faster?

Asked By: jivky

||

Answers:

You say that your typical polygon will have from 25% to 33% of the bounding box consisting of valid area. Worst case, if you select a random point within that bounding box, you have a 25% chance of it being good. Choose 4 points, and your odds go up to 68%. By the time you’ve tried 17, you’re 99% likely to have found a good one.

Checking a point to see if it’s within a polygon can be pretty efficient. See the question What’s the fastest way of checking if a point is inside a polygon in python for some possibilities. A robust algorithm won’t have any trouble dealing with polygons having holes as shown in your question. Since all the edges of your polygon are horizontal or vertical lines it might be possible to do even better, but it might not be worth it.

This will almost certainly be faster than generating the 100000 or so valid points within the polygon, just to choose one.

Answered By: Mark Ransom
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.