2014-04-12 71 views
0

我需要檢測圖像中的所有矩形。鏈接缺失(通過Canny)邊緣

這裏是我的代碼:

Mat PolygonsDetection(Mat src) 
{ 
    Mat gray; 
    cvtColor(src, gray, CV_BGR2GRAY); 

    Mat bw; 
    Canny(src, bw, 50, 200, 3, true); 
    imshow("canny", bw); 

    morphologyEx(bw, bw, MORPH_CLOSE, cv::noArray(),cv::Point(-1,-1),1); 

    imshow("morph", bw); 

    vector<vector<Point>> countours; 
    findContours(bw.clone(), countours, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE); 

    vector<Point> approx; 
    Mat dst = src.clone(); 

    for(int i = 0; i < countours.size(); i++) 
    { 
     approxPolyDP(Mat(countours[i]), approx, arcLength(Mat(countours[i]), true) * 0.01, true); 

     if (approx.size() >= 4 && (approx.size() <= 6)) 
     { 
      int vtc = approx.size(); 
      vector<double> cos; 
      for(int j = 2; j < vtc + 1; j++) 
       cos.push_back(Angle(approx[j%vtc], approx[j-2], approx[j-1])); 

      sort(cos.begin(), cos.end()); 

      double mincos = cos.front(); 
      double maxcos = cos.back(); 

      if (vtc == 4)// && mincos >= -0.5 && maxcos <= 0.5) 
      { 
       Rect r = boundingRect(countours[i]); 
       double ratio = abs(1 - (double)r.width/r.height); 

       line(dst, approx.at(0), approx.at(1), cvScalar(0,0,255),4); 
       line(dst, approx.at(1), approx.at(2), cvScalar(0,0,255),4); 
       line(dst, approx.at(2), approx.at(3), cvScalar(0,0,255),4); 
       line(dst, approx.at(3), approx.at(0), cvScalar(0,0,255),4); 
       SetLabel(dst, "RECT", countours[i]); 
      } 
     } 
    } 

    return dst; 
} 

這裏是我的輸出:

enter image description here

而是17的矩形(16小和1大)我只拿到了12的矩形。 我是新的opencv中,也許我錯誤的參數傳遞給Canny函數和形態學... 所以,我的問題: 我有什麼錯? 我該如何修復?

+0

嘗試使用坎尼參數打轉轉尋找獨立的組件;第一個特別是第二個閾值。像Canny(src,bw,50,100,3,true);''可能會讓你到那裏。 – HugoRune

+0

這不是dublicate。我檢查瞭解決方案,它不工作。 – Rougher

回答

0

你可以做的是使用通常的侵蝕擴張技巧。在Matlab中,我通常做以下創建一個面具。這使得線條更大並且流動在一起。

%Create Structuring element 
sel = strel('disk', 1); 
% bw is the black and white (binary image) created using e.g. Otsu thresholding 
bw2 = imcomplement(bw); 
bw3 = imerode(bw2, sel); 
bw4 = imdilate(bw3, sel); 
tightmask = imcomplement(bw4); 

我用這個經常用於圖像