OpenCV正方形:过滤输出

4

以下是方框检测示例的输出结果,我的问题是如何过滤这些方框:

http://ozsulastik.com/ocvsquares.png

  • 第一个问题是它会为同一区域绘制多条线;
  • 第二个问题是我只需要检测物体而不是整张图片。

另一个问题是我必须仅选择最大的物体,而不是整张图片。

以下是用于检测的代码:

static void findSquares( const Mat& image, vector >& squares ){

squares.clear();

Mat pyr, timg, gray0(image.size(), CV_8U), gray;

// down-scale and upscale the image to filter out the noise
pyrDown(image, pyr, Size(image.cols/2, image.rows/2));
pyrUp(pyr, timg, image.size());
vector<vector<Point> > contours;

// find squares in every color plane of the image
for( int c = 0; c < 3; c++ )
{
    int ch[] = {c, 0};
    mixChannels(&timg, 1, &gray0, 1, ch, 1);

    // try several threshold levels
    for( int l = 0; l < N; l++ )
    {
        // hack: use Canny instead of zero threshold level.
        // Canny helps to catch squares with gradient shading
        if( l == 0 )
        {
            // apply Canny. Take the upper threshold from slider
            // and set the lower to 0 (which forces edges merging)
            Canny(gray0, gray, 0, thresh, 5);
            // dilate canny output to remove potential
            // holes between edge segments
            dilate(gray, gray, Mat(), Point(-1,-1));
        }
        else
        {
            // apply threshold if l!=0:
            gray = gray0 >= (l+1)*255/N;
        }

        // find contours and store them all as a list
        findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);

        vector<Point> approx;

        // test each contour
        for( size_t i = 0; i < contours.size(); i++ )
        {
            approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);

            if( approx.size() == 4 &&
                fabs(contourArea(Mat(approx))) > 1000 &&
                isContourConvex(Mat(approx)) )
            {
                double maxCosine = 0;

                for( int j = 2; j < 5; j++ )
                {
                    // find the maximum cosine of the angle between joint edges
                    double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
                    maxCosine = MAX(maxCosine, cosine);
                }

                if( maxCosine < 0.3 )
                    squares.push_back(approx);
            }
        }
    }
}

}


计算检测到的正方形面积,然后取最大值。您可以通过检查检测到的正方形是否小于图像的95%来尝试排除“整个图像正方形”等情况。 - iiro
请添加原始图像,以便用户可以使用它并演示您的工作。 - Abid Rahman K
原始图片 http://ozsulastik.com/p1.jpg http://ozsulastik.com/p2.jpg - Kaan Seyitogullari
我之前考虑过这个问题,但是处理起来需要时间,因为有时候会在同一区域绘制20条线,并且我提供的图像数组列表有40个或更多,我不认为这是正确的方式。谢谢回答。 - Kaan Seyitogullari
1个回答

4
你需要查看findContours()的标志。您可以设置一个名为CV_RETR_EXTERNAL的标志,它只返回最外层轮廓(其中所有轮廓都被丢弃)。这可能会返回整个帧,因此您需要缩小搜索范围,以便不检查帧边界。使用函数copyMakeBorder()来完成这个任务。我还建议您删除dilate函数,因为它可能会在线的两侧产生重复的轮廓(如果删除dilate,您甚至可能不需要边框)。以下是我的输出: enter image description here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接