Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV most efficient way to find a point in a polygon

I have a dataset of 500 cv::Point.

For each point, I need to determine if this point is contained in a ROI modelized by a concave polygon. This polygon can be quite large (most of the time, it can be contained in a bounding box of 100x400, but it can be larger)

For that number of points and that size of polygon, what is the most efficient way to determine if a point is in a polygon?

  • using the pointPolygonTest openCV function?
  • building a mask with drawContours and finding if the point is white or black in the mask?
  • other solution? (I really want to be accurate, so convex polygons and bounding boxes are excluded).
like image 867
Simon Ninon Avatar asked Oct 28 '25 14:10

Simon Ninon


2 Answers

In general, to be both accurate and efficient, I'd go with a two-step process.

  • First, a bounding box on the polygon. It's a quick and simple matter to see which points are not inside the box. With that, you can discard several points right off the bat.
  • Secondly, pointPolygonTest. It's a relatively costly operation, but the first step guarantees that you will only perform it for those points that need better accuracy.

This way, you mantain accuracy but speed up the process. The only exception is when most points will fall inside the bounding box. In that case, the first step will almost always fail and thus won't optimise the algorithm, will actually make it slightly slower.

like image 190
legrojan Avatar answered Oct 31 '25 06:10

legrojan


Quite some time ago I had exactly the same problem and used the masking approach (second point of your statement). I was testing this way datasets containing millions of points and found this solution very effective.

like image 22
Amadeusz Avatar answered Oct 31 '25 07:10

Amadeusz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!