opencv - 矩形数组OpenCv中的交点

标签 opencv detection intersection

我尝试检测视频中的某些移动物体。如果任何两个/三个+矩形重叠/相交,我希望它们更改颜色。
我已经尝试过这样的事情:

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.
    }   

但是,如果您想绘制每个相交区域,它会变得有些复杂,但是也可以完成...

关于opencv - 矩形数组OpenCv中的交点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34883404/

相关文章:

r - 如何在 R 中通过网络检测远程文件夹中新添加的文件?

java - 红色圆圈样检测 |打开简历 | java

javascript - 用于将 2D 多边形横截面转换为 1D 几何图形的工具或库?

iOS 以编程方式添加 UITableView 部分并重新加载它

wpf - 在不使用 anchor 的情况下通过一条线连接两个 WPF Canvas 元素?

python - 我如何用python中的逻辑索引替换for循环中的图像屏蔽?

javascript - 用于 web/javascript 的 OpenCV

Windows Server 2012 R2 x64 上带有 Python 3.6.4 的 OpenCV 导入 cv2 : DLL not found

python - 如果更改图像大小会影响检测图像中的颜色对象:OpenCV python

c - 您如何在运行时使用 GCC 和内联 asm 检测 CPU 架构类型?