How to check if one circuit is nested / embedded in opencv

+7
source share
2 answers

Use cv::pointPolygonTest(InputArray contour, Point2f pt, bool measureDist) to find out if a point from the contour is inside another.

You should check for borderline cases (the first point you select is common to both polygons, etc.)

 if(pointPolygonTest(contour, pointFromOtherContour, false) > 0) { // it is inside } 

The function determines whether the point is inside the contour, outside, or lies on the edge (or coincides with the vertex). It returns a positive (internal), negative (external) or zero (edge) value , respectively.

When measureDist=false , the return value is +1, -1, and 0, respectively. Otherwise, the return value will be the sign distance between the point and the nearest contour of the contour.

+6
source

If you know that the contours are closed (in the sense of 4 connectives), then you can probably use the ray-infinity test, which is more often used to check if points are inside closed polygons. (Also assuming that the contours do not intersect, which apparently they cannot.)

Take any point on the contour of the candidate and go from there to β€œinfinity” in any direction (select the axis aligned one at a time for ease of implementation): if you get to the edge of your image and cross the outer contour an odd number of times, then the contour that you started is inside this circuit.

The 'intersection' of the outer contour is actually a bit more complicated, for example:

  . 1 1 1 1 1 1 1 . 1 . . XXX 1 . 1 . . X . X 1 <-.-1-1-.-XXX 1 : here a naiive implementation counts two crossings . . 1 1 1 1 1 1 

So, to check if the β€œray” crosses the contour at a point, you really need to consider the neighboring 3x3 points. I think you will get many cases that look something like this:

  . . . <-1-1 1 // not crossing . . . 1 . 1 <-1-1 1 // not crossing . . . . . 1 <-1-1 1 // crossing . . . 1 . . <-1-1 1 // crossing . . . 

I'm not 100% sure that you can build a consistent test for intersections of a 4-connected contour based on 3x3 neighborhoods, but it seems likely that it is.

All this depends, of course, on a closed external circuit.

+1
source