矩形数组 OpenCv 中的交集

Intersection in an array of rectangles OpenCv

我尝试检测视频中的某些移动物体。如果有任何 two/three+ 矩形 overlap/intersect 我希望它们改变颜色。 我试过这样的事情:

for (size_t i = 0; i < contours.size(); i++)
        {
            Scalar color = Scalar(0.0, 255.0, 0.0);
            // intersection
            original = boundRect[i];
                for (size_t j = 0; j < boundRect.size(); j++){
                  if (j == i) continue; // the same rectangle
                  match = boundRect[j];
                  if ((original & match).area() > 0) color = Scalar(0.0, 0.0, 255.0);
                  else color = Scalar(0.0, 255.0, 0.0);
                }
                // draw the rectangle
                rectangle(frame, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0);
        }   

它有时确实有效,但现在总是有效。我不知道我这样做是否正确,或者是否有更好的方法。

您似乎以正确的方式计算相交,但您只为每个 i 绘制一次结果。如果矩形 j 不与 i 相交,您将再次覆盖更改后的颜色。只需删除设置颜色的 else 大小写,或者记住一个矩形是否(或多久)与另一个矩形相交。例如:

for (size_t i = 0; i < contours.size(); i++)
    {
        int nIntersections = 0;
        // intersection
        original = boundRect[i];
            for (size_t j = 0; j < boundRect.size(); j++){
              if (j == i) continue; // the same rectangle
              match = boundRect[j];
              if ((original & match).area() > 0)
              {
                  nIntersections++;
                  // if you only want to know whether intersections appear or not, you can stop the inner for-loop here, by using j=boundRect.size(); continue; or break;
              }
            }
            // draw the rectangle
            cv::Scalar color(0,255,0);
            if(nIntersections > 0) color = cv::Scalar(0,0,255);
            // adjust for different 
            // if(nIntersections > 1) color = ...
            rectangle(frame, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0);
            // for simplicity you can just call rectangle(frame, boundRect[i], color, 2, 8, 0); without getting top-left and bottom-right points first. cv::rectangle uses cv::Rect as a parameter directly if you like.
    }   

如果你想绘制每个交叉区域,它会变得有点复杂,但也可以做到...