11

I have the contours of 2 polygons (as vector of cv::Point2d).

I would like to calculate the area of intersection between them

What is the easiest way to get it?

Thank you very much!

Ron

Ron Gross
  • 1,474
  • 5
  • 19
  • 34

3 Answers3

12

Draw the shapes with CV_FILLED in two images and AND them. Area is: CountNonZero(bitwise_and(ShapeAImage,ShapeBImage)).

LovaBill
  • 5,107
  • 1
  • 24
  • 32
4

You can find intersection polygon wth Clipper library

//create clipper polygons from your points
c.AddPolygons(subj, ptSubject);
c.AddPolygons(clip, ptClip);
c.Execute(ctIntersection, solution, pftNonZero, pftNonZero);

then calc area of this polygon

MBo
  • 77,366
  • 5
  • 53
  • 86
  • [`contourArea()`](https://docs.opencv.org/4.7.0/d3/dc0/group__imgproc__shape.html#ga2c759ed9f497d4a618048a2f56dc97f1) from OpenCV can also calculate area of polygon – n0099 Feb 24 '23 at 08:02
  • @n0099 But we have to get intersection first - much more complex problem – MBo Feb 24 '23 at 09:42
  • [`cv::intersectConvexConvex()`](https://docs.opencv.org/4.7.0/d3/dc0/group__imgproc__shape.html#ga06eed475945f155030f2135a7f25f11d) can calculate the intersection polygon and its area if the two input polygons are [convex](https://en.wikipedia.org/wiki/Convex_polygon). – n0099 Mar 09 '23 at 18:49
3

The easiest method to code goes like this:

cv::Rect BoundingBox;
int IntersectionArea = 0;
//insert Min-Max X,Y to create the BoundingBox

for (every y inside boundingbox)
     for (every x inside boundingbox)
         if (PointPolygonTest(x,y,Contour1) && PointPolygonTest(x,y,Contour2))
             IntersectionArea++;
Boyko Perfanov
  • 3,007
  • 18
  • 34
  • 2
    Unfortunately this won't help me because I need is to be more accurate then using a bounding box... The polygons can be in wierd shapes (L shape for example) and bounding box just can't handle those cases. Thank you any way! – Ron Gross Jul 23 '13 at 13:08
  • 4
    It IS accurate. The bounding box is used as optimization to reduce the number of pixels that are tested for being inside both polygons. Technically you can do every "x" and every "y" in the image, and it would produce the same results. – Boyko Perfanov Jul 23 '13 at 13:10
  • 2
    This solution would be very slow. – nn0p Jun 14 '16 at 05:11