2013-02-20 116 views
2

这里是出放平方检测例的我的问题是过滤此正方形OpenCV的正方形:滤波输出

http://ozsulastik.com/ocvsquares.png

  • 第一个问题是它的拉伸超过一人线相同的面积;
  • 第二个是我只需要检测对象不是所有的图像。

另一个问题是我必须采取最大的对象,除了所有图像。

http://ozsulastik.com/ocvsquares2.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); 
      } 
     } 
    } 
} 

}

+0

计算检测到的平方区域,然后取最大的一个。您可以尝试通过检查检测到的方块小于图像的95%来解除“整幅图像方块”。 – iiro 2013-02-20 09:05:30

+0

也可以添加原始图像,以便用户可以对其进行操作并演示。 – 2013-02-20 09:05:34

+0

原始图像 http://ozsulastik.com/p1.jpg http://ozsulastik.com/p2.jpg – 2013-02-20 09:11:49

回答

3

你需要看一看标志为findContours()。你可以设置一个名为CV_RETR_EXTERNAL的标志,它将只返回最外层轮廓(它内部的所有轮廓都被丢弃)。这可能会返回整个框架,所以您需要缩小搜索范围,以便它不检查您的框架边界。使用函数copyMakeBorder()完成此操作。我还建议删除您的扩张功能,因为它可能会导致线条两侧出现重复的轮廓(如果删除扩张部分,您甚至可能不需要边框)。这是我的输出: enter image description here