1. 程式人生 > >【OpenCV學習筆記 010】提取直線、輪廓及連通區域

【OpenCV學習筆記 010】提取直線、輪廓及連通區域

一、Canny運算元檢測輪廓   (http://blog.csdn.net/davebobo/article/details/52583167)

1.概念及原理

(1)之前我們是對梯度大小進行閾值化以得到二值的邊緣影象。但是這樣做有兩個缺點。其一是檢測到的邊緣過粗,難以實現物體的準確定位。其二是很難找到合適的閾值既能足夠低於檢測到所有重要邊緣,又能不至於包含過多次要邊緣,這就是Canny演算法嘗試解決的問題。

(2)Canny運算元通常是基於Sobel運算元,當然也可以使用其他梯度運算元。其思想是使用一個低閾值一個高閾值來確定哪些點屬於輪廓。低閾值的作用主要是包括所有屬於明顯影象輪廓的邊緣畫素。高閾值的作用是定義所有重要輪廓的邊緣。

Canny運算元是組合低閾值和高閾值這兩幅邊緣圖以生成最優的輪廓圖。這種使用雙閾值以得到二值影象的策略被稱為磁滯閾值化。

2.實驗

使用Canny運算元檢測輪廓

原始碼示例(很簡單)

  1. <pre name="code"class="cpp">#include<iostream>      
  2. #include <opencv2/core/core.hpp>    
  3. #include <opencv2/highgui/highgui.hpp> 
  4. #include<imgproc/imgproc.hpp>  
  5. usingnamespace std;  
  6. using
    namespace cv;  
  7. int main(){  
  8.     Mat image = imread("tree.jpg", 0);  
  9.     namedWindow("image");  
  10.     imshow("image", image);  
  11.     Mat contours;  
  12.     Canny(image,    //灰度圖
  13.         contours,   //輸出輪廓
  14.         125,    //低閾值
  15.         350);   //高閾值
  16.     //因為正常情況下輪廓是用非零畫素表示 我們反轉黑白值
  17.     Mat contoursInv;    //反轉後的影象
  18.     threshold(contours,  
  19.         contoursInv,   
  20.         128,    //低於該值的畫素
  21.         255,    //將變成255
  22.         THRESH_BINARY_INV);  
  23.     namedWindow("contoursInv");   
  24.     imshow("contoursInv", contoursInv);  
  25.     waitKey(0);  
  26.     return 0;  
  27. }  
實驗效果圖

二、霍夫變換檢測直線

1.概念及原理

(1)霍夫變換是檢測直線的經典演算法,最初只用於檢測直線,後被擴充套件能夠檢測其他簡單結構。在霍夫變換中,直線用方程表示為:,p是指直線到影象原點(左上角)的距離,θ則是與直線垂直的角度。

(2)霍夫變換使用二維的累加器以統計特定的直線被識別了多少次。目的是找到二值影象中經過足夠多數量的點的所有直線,它分析每個單獨的畫素點,識別出所有可能經過它的直線,當同一條直線穿過許多點時,說明這條直線明顯的存在。

2.實驗

先用Canny運算元獲取影象輪廓,然後基於霍夫變換檢測直線。

原始碼示例

  1. #define _USE_MATH_DEFINES
  2. #include <math.h>
  3. #include<iostream>  
  4. #include <opencv2/core/core.hpp>    
  5. #include <opencv2/highgui/highgui.hpp> 
  6. #include<imgproc/imgproc.hpp>  
  7. usingnamespace std;  
  8. usingnamespace cv;  
  9. int main(){  
  10.     Mat image = imread("tree.jpg");  
  11.     namedWindow("image");  
  12.     imshow("image", image);  
  13.     Mat result;  
  14.     cvtColor(image, result, CV_BGR2GRAY);  
  15.     //應用Canny演算法
  16.     Mat contours;  
  17.     Canny(result,   //灰度圖
  18.         contours,   //輸出輪廓
  19.         125,    //低閾值
  20.         350);   //高閾值
  21.     //Hough 變換檢測直線
  22.     vector <Vec2f>lines;  
  23.     HoughLines(contours,    //一幅邊緣影象
  24.         lines,  //代表檢測到的浮點數
  25.         1,M_PI / 180,   // 步進尺寸
  26.         80);    //最小投票數
  27.     //繪製每條線
  28.     vector<Vec2f>::const_iterator it = lines.begin();  
  29.     while (it!=lines.end())  
  30.     {  
  31.         float rho = (*it)[0];   //距離rho
  32.         float theta = (*it)[1]; //角度theta
  33.         if (theta<M_PI / 4. || theta>3.*M_PI / 4.)    //垂直線
  34.         {  
  35.             //線與第一行的交點
  36.             Point pt1(rho / cos(theta), 0);  
  37.             //線與最後一行的交點
  38.             Point pt2((rho - result.rows*sin(theta)) / cos(theta), result.rows);  
  39.             //繪製白線
  40.             line(image, pt1, pt2, Scalar(255), 1);  
  41.         }  
  42.         else//水平線
  43.         {  
  44.             //線與第一列的交點
  45.             Point pt1(0, rho / sin(theta));  
  46.             //線與最後一列的交點
  47.             Point pt2(result.cols, (rho - contours.cols*cos(theta)) / sin(theta));  
  48.             //繪製白線
  49.             line(image, pt1, pt2, Scalar(255), 1);  
  50.         }  
  51.         ++it;  
  52.     }  
  53.     cvNamedWindow("hough");  
  54.     imshow("hough", image);  
  55.     waitKey(0);  
  56.     return 0;  
  57. }  
程式執行結果

函式原型

  1. //! finds lines in the black-n-white image using the standard or pyramid Hough transform
  2. CV_EXPORTS_W void HoughLines( InputArray image, OutputArray lines,  
  3.                               double rho, double theta, int threshold,  
  4.                               double srn=0, double stn=0 );  
引數說明
第一個引數:一幅包含一組點的二值影象,通常是一幅邊緣影象,比如來自Canny運算元。
第二個引數:輸出Vec2f向量,每個元素元素都是代表檢測到的直線的浮點數(ρ,θ)。
第三、四個引數:直線搜尋時的步進尺寸
第五個引數:能夠被檢測為直線所需要的最小投票數目。
霍夫變換僅僅查詢邊緣的一種排列方式,因為意外的畫素排列或是多條線穿過同一組畫素很有可能帶來錯誤的檢測,所以對其演算法進行改進即概率霍夫變換,我們將其封裝到LineFinder類中進行使用。
程式原始碼
  1. #define _USE_MATH_DEFINES
  2. #include <math.h>
  3. #include<iostream>  
  4. #include <opencv2/core/core.hpp>    
  5. #include <opencv2/highgui/highgui.hpp> 
  6. #include<imgproc/imgproc.hpp>  
  7. usingnamespace std;  
  8. usingnamespace cv;  
  9. class LineFinder{  
  10. private:  
  11.     Mat img;    //原圖
  12.     vector<Vec4i>lines;   //向量中檢測到的直線的端點
  13.     //累加器的解析度
  14.     double deltaRho;  
  15.     double deltaTheta;  
  16.     int minVote;    //直線被接受時所需的最小投票數
  17.     double minLength;   //直線的最小長度
  18.     double maxGap;  //沿著直線方向的最大缺口
  19. public:  
  20.     //預設的累加器的解析度為單個畫素即1  不設定缺口及最小長度的值
  21.     LineFinder() :deltaRho(1), deltaTheta(M_PI / 180), minVote(10), minLength(0.), maxGap(0.){};  
  22.     //設定累加器的解析度
  23.     void setAccResolution(double dRho, double dTheta){  
  24.         deltaRho = dRho;  
  25.         deltaTheta = dTheta;  
  26.     }  
  27.     //設定最小投票數
  28.     void setMinVote(int minv){  
  29.         minVote = minv;  
  30.     }  
  31.     //設定缺口及最小長度
  32.     void setLineLengthAndGap(double length, double gap){  
  33.         minLength = length;  
  34.         maxGap = gap;  
  35.     }  
  36.     //使用概率霍夫變換
  37.     vector<Vec4i>findLines(Mat &binary){  
  38.         lines.clear();  
  39.         HoughLinesP(binary, lines, deltaRho, deltaTheta, minVote, minLength, maxGap);  
  40.         return lines;  
  41.     }  
  42.     //繪製檢測到的直線
  43.     void drawDetectedLines(Mat &image,Scalar color = Scalar(255,255,255)){  
  44.         //畫線
  45.         vector<Vec4i>::const_iterator it2 = lines.begin();  
  46.         while (it2!=lines.end())  
  47.         {  
  48.             Point pt1((*it2)[0],(*it2)[1]);  
  49.             Point pt2((*it2)[2], (*it2)[3]);  
  50.             line(image, pt1, pt2, color);  
  51.             ++it2;  
  52.         }  
  53.     }  
  54. };  
  55. int main(){  
  56.     Mat image = imread("tree.jpg");  
  57.     namedWindow("image");  
  58.     imshow("image", image);  
  59.     Mat result;  
  60.     cvtColor(image, result, CV_BGR2GRAY);  
  61.     //應用Canny演算法
  62.     Mat contours;  
  63.     Canny(result,   //灰度圖
  64.         contours,   //輸出輪廓
  65.         125,    //低閾值
  66.         350);   //高閾值
  67.     //建立LineFinder例項
  68.     LineFinder finder;  
  69.     //設定概率Hough引數
  70.     finder.setLineLengthAndGap(100, 20);  
  71.     finder.setMinVote(80);  
  72.     //檢測並繪製直線
  73.     vector<Vec4i>lines = finder.findLines(contours);  
  74.     finder.drawDetectedLines(image);  
  75.     cvNamedWindow("Detected Lines with HoughP");  
  76.     imshow("Detected Lines with HoughP", image);  
  77.     waitKey(0);  
  78.     return 0;  
  79. }  
測試結果

三、直線擬合一組點

1.概念及原理

(1)Hough 變換可以提取影象中的直線。但是提取的直線的精度不高。而很多場合下,我們需要精確的估計直線的引數,這時就需要進行直線擬合。直線擬合的方法很多,比如一元線性迴歸就是一種最簡單的直線擬合方法。但是這種方法不適合用於提取影象中的直線。因為這種演算法假設每個資料點的X 座標是準確的,Y 座標是帶有高斯噪聲的。可實際上,影象中的每個資料點的XY 座標都是帶有噪聲的。Opencv通過最小化每個點到直線的距離之和進行求解,有多個距離函式, CV_DIST_L1 、CV_DIST_L2 、CV_DIST_C  、CV_DIST_L12、 CV_DIST_FAIR 、CV_DIST_WELSCH和 CV_DIST_HUBER ,其中最快的是歐式距離即CV_DIST_L2它對應的是標準的二乘法。

2.實驗

原始碼示例

  1. #define _USE_MATH_DEFINES
  2. #include <math.h>
  3. #include<iostream>  
  4. #include <opencv2/core/core.hpp>    
  5. #include <opencv2/highgui/highgui.hpp> 
  6. #include<imgproc/imgproc.hpp>  
  7. usingnamespace std;  
  8. usingnamespace cv;  
  9. int main(){  
  10.     Mat image = imread("tree.jpg");  
  11.     namedWindow("image");  
  12.     imshow("image", image);  
  13.     Mat result;  
  14.     cvtColor(image, result, CV_BGR2GRAY);  
  15.     //應用Canny演算法
  16.     Mat contours;  
  17.     Canny(result,    //灰度圖
  18.         contours,    //輸出輪廓
  19.         125,    //低閾值
  20.         350);    //高閾值
  21.     //建立LineFinder例項
  22.     LineFinder finder;  
  23.     //設定概率Hough引數
  24.     finder.setLineLengthAndGap(100, 20);  
  25.     finder.setMinVote(80);  
  26.     //檢測並繪製直線
  27.     vector<Vec4i>lines = finder.findLines(contours);  
  28.     int n = 0;    //選擇line 0
  29.     //黑色影象
  30.     Mat oneline(contours.size(), CV_8U, Scalar(0));  
  31.     //白色直線
  32.     line(oneline,  
  33.         Point(lines[n][0], lines[n][1]),  
  34.         Point(lines[n][2], lines[n][3]),  
  35.         Scalar(255),  
  36.         5  
  37.         );  
  38.     //輪廓與白線進行AND操作
  39.     bitwise_and(contours, oneline, oneline);  
  40.     Mat oneLineInv;    //白色直線反轉後的影象
  41.     threshold(oneline,  
  42.         oneLineInv,  
  43.         128,    //低於該值的畫素
  44.         255,    //將變成255
  45.         THRESH_BINARY_INV);  
  46.     cvNamedWindow("One line");  
  47.     imshow("One line", oneLineInv);  
  48.     //將指定直線相關的點置入cv::Points型別的std::vector中
  49.     vector<Point>points;  
  50.     //遍歷畫素得到所有點的位置
  51.     for (int y = 0; y < oneline.rows; y++)  
  52.     {  
  53.         //y行
  54.         uchar *rowPtr = oneline.ptr<uchar>(y);  
  55.         for (int x = 0; x < oneline.cols; x++)  
  56.         {  
  57.             //x列
  58.             //如果位於輪廓上
  59.             if (rowPtr[x])  
  60.             {  
  61.                 points.push_back(Point(x, y));  
  62.             }  
  63.         }  
  64.     }  
  65.     Vec4f lineVec;  
  66.     fitLine(Mat(points),  
  67.         lineVec,  
  68.         CV_DIST_L2,    //距離型別
  69.         0,    //L2距離不使用該引數
  70.         0.01,0.01);    //精確值
  71.     int x0 = lineVec[2];    //直線上的點
  72.     int y0 = lineVec[3];  
  73.     int x1 = x0 - 200 * lineVec[0];    //使用單元向量
  74.     int y1 = y0 - 200 * lineVec[1];    //新增長度為200的向量
  75.     cv::line(result, Point(x0, y0), Point(x1, y1), Scalar(0), 3);  
  76.     cvNamedWindow("Estimated line");  
  77.     imshow("Estimated line", result);  
  78.     waitKey(0);  
  79.     return 0;  
  80. }  
擬合效果圖


實驗過程說明

(1)首先識別出可能排列成直線的點,即我們使用霍夫變換檢測到的一條直線。

(2)接著得到僅包含指定直線相關的點即oneline,然後將集合中的點放置在cv::Pointdes的vector中。

(3)呼叫cv::fitLine函式找到最合適的線。

fitLine函式原型及說明

  1. void fitLine( InputArray points,   
  2.     OutputArray line,   
  3.     int distType,  
  4.     double param,   
  5.     double reps,   
  6.     double aeps );  

distType 指定擬合函式的型別,可以取 CV_DIST_L2、CV_DIST_L1、CV_DIST_L12、CV_DIST_FAIR、CV_DIST_WELSCH、CV_DIST_HUBER。

param 就是 CV_DIST_FAIR、CV_DIST_WELSCH、CV_DIST_HUBER 公式中的C。如果取 0,則程式自動選取合適的值。

reps 表示直線到原點距離的精度,建議取 0.01。
aeps 表示直線角度的精度,建議取 0.01。

四、提取連通區域的輪廓

1.概念及原理

(1)Opencv中提供了一個簡單的函式用於提取連通區域cv::findContours。它是通過系統的掃描影象直到遇到連通區域的一個點,以它為起始點,跟蹤它的輪廓,標記邊界上的元素,當輪廓完整閉合,掃描回到上一個位置,直到再次發現新的成分。

2.實驗

提取下圖的連通區域輪廓。


程式例項

  1. #include<iostream>  
  2. #include <opencv2/core/core.hpp>    
  3. #include <opencv2/highgui/highgui.hpp> 
  4. #include<imgproc/imgproc.hpp>  
  5. usingnamespace std;  
  6. usingnamespace cv;  
  7. int main(){  
  8.     Mat image = cvLoadImage("group.jpg");  
  9.     Mat grayImage;  
  10.     cvtColor(image, grayImage, CV_BGR2GRAY);  
  11.     //轉換為二值圖  
  12.     Mat binaryImage;  
  13.     threshold(grayImage, binaryImage, 90, 255, CV_THRESH_BINARY);  
  14.     //二值圖 這裡進行了畫素反轉,因為一般我們用255白色表示前景(物體),用0黑色表示背景  
  15.     Mat reverseBinaryImage;  
  16.     bitwise_not(binaryImage, reverseBinaryImage);  
  17.     vector <vector<Point>>contours;  
  18.     findContours(reverseBinaryImage,  
  19.         contours,   //輪廓的陣列
  20.         CV_RETR_EXTERNAL,   //獲取外輪廓
  21.         CV_CHAIN_APPROX_NONE);  //獲取每個輪廓的每個畫素
  22.     //在白色影象上繪製黑色輪廓
  23.     Mat result(reverseBinaryImage.size(), CV_8U, Scalar(255));  
  24.     drawContours(result, contours,  
  25.         -1, //繪製所有輪廓
  26.         Scalar(0),  //顏色為黑色
  27.         2); //輪廓線的繪製寬度為2
  28.     namedWindow("contours");  
  29.     imshow("contours", result);  
  30.     //移除過長或過短的輪廓
  31.     int cmin = 100; //最小輪廓長度
  32.     int cmax = 1000;    //最大輪廓
  33.     vector<vector<Point>>::const_iterator itc = contours.begin();  
  34.     while (itc!=contours.end())  
  35.     {  
  36.         if (itc->size() < cmin || itc->size() > cmax)  
  37.             itc = contours.erase(itc);  
  38.         else
  39.             ++itc;  
  40.     }  
  41.     //在白色影象上繪製黑色輪廓
  42.     Mat result_erase(binaryImage.size(), CV_8U, Scalar(255));  
  43.     drawContours(result_erase, contours,  
  44.         -1, //繪製所有輪廓
  45.         Scalar(0),  //顏色為黑色
  46.         2); //輪廓線的繪製寬度為2
  47.     namedWindow("contours_erase");  
  48.     imshow("contours_erase", result_erase);  
  49.     waitKey(0);  
  50.     return 0;  
  51. }  
提取結果


五、計算連通區域的形狀描述符

1.概念及原理

連通區域通常對應於場景中的某個物體,為了識別該物體或者將它與其他影象元素作比較,我們需要進行一些測量儀來獲取它的特徵,這裡我們就利用Opencv中可用的一些形狀描述符。

2.實驗

利用Opencv中的形狀描述符來描述上例提取到的輪廓。

原始碼示例

  1. #include<iostream>  
  2. #include <opencv2/core/core.hpp>    
  3. #include <opencv2/highgui/highgui.hpp> 
  4. #include<imgproc/imgproc.hpp>  
  5. usingnamespace std;  
  6. usingnamespace cv;  
  7. int main(){  
  8.     Mat image = cvLoadImage("group.jpg");  
  9.     Mat grayImage;  
  10.     cvtColor(image, grayImage, CV_BGR2GRAY);  
  11.     //轉換為二值圖  
  12.     Mat binaryImage;  
  13.     threshold(grayImage, binaryImage, 90, 255, CV_THRESH_BINARY);  
  14.     //二值圖 這裡進行了畫素反轉,因為一般我們用255白色表示前景(物體),用0黑色表示背景  
  15.     Mat reverseBinaryImage;  
  16.     bitwise_not(binaryImage, reverseBinaryImage);  
  17.     vector <vector<Point>>contours;  
  18.     findContours(reverseBinaryImage,  
  19.         contours,   //輪廓的陣列
  20.         CV_RETR_EXTERNAL,   //獲取外輪廓
  21.         CV_CHAIN_APPROX_NONE);  //獲取每個輪廓的每個畫素
  22.     //在白色影象上繪製黑色輪廓
  23.     Mat result(reverseBinaryImage.size(), CV_8U, Scalar(255));  
  24.     drawContours(result, contours,  
  25.         -1, //繪製所有輪廓
  26.         Scalar(0),  //顏色為黑色
  27.         2); //輪廓線的繪製寬度為2
  28.     namedWindow("contours");  
  29.     imshow("contours", result);  
  30.     //移除過長或過短的輪廓
  31.     int cmin = 100; //最小輪廓長度
  32.     int cmax = 1000;    //最大輪廓
  33.     vector<vector<Point>>::const_iterator itc = contours.begin();  
  34.     while (itc!=contours.end())  
  35.     {  
  36.         if (itc->size() < cmin || itc->size() > cmax)  
  37.             itc = contours.erase(itc);  
  38.         else
  39.             ++itc;  
  40.     }  
  41.     //在白色影象上繪製黑色輪廓
  42.     Mat result_erase(binaryImage.size(), CV_8U, Scalar(255));  
  43.     drawContours(result_erase, contours,  
  44.         -1, //繪製所有輪廓
  45.         Scalar(0),  //顏色為黑色
  46.         2); //輪廓線的繪製寬度為2
  47.     //namedWindow("contours_erase");
  48.     //imshow("contours_erase", result_erase);
  49.     //測試包圍盒
  50.     Rect r0 = boundingRect(Mat(contours[0]));  
  51.     rectangle(result_erase, r0, Scalar(128), 2);  
  52.     Rect r1 = boundingRect(Mat(contours[1]));  
  53.     rectangle(result_erase, r1, Scalar(128), 2);  
  54.     //測試最小包圍圓
  55.     float radius;  
  56.     Point2f center;  
  57.     minEnclosingCircle(Mat(contours[2]), center, radius);  
  58.     circle(result_erase, Point(center), static_cast<int>(radius), Scalar(128), 2);  
  59.     //測試多邊形近似
  60.     vector <Point> poly;  
  61.     approxPolyDP(Mat(contours[3]),  
  62.         poly,  
  63.         5,  //近似的精確度
  64.         true);  //這是個閉合形狀
  65.     //遍歷每個片段進行繪製
  66.     vector<Point>::const_iterator itp = poly.begin();  
  67.     while (itp != (poly.end() - 1))  
  68.     {  
  69.         line(result_erase, *itp, *(itp + 1), Scalar(128), 2);  
  70.         ++itp;  
  71.     }  
  72.     //首尾用直線相連
  73.     line(result_erase, *(poly.begin()), *(poly.end() - 1), Scalar(128), 2);  
  74.     //凸包是另一種多邊形近似,計算凸包
  75.     vector <Point> hull;  
  76.     convexHull(Mat(contours[4]), hull);  
  77.     vector<Point>::const_iterator ith = hull.begin();  
  78.     while (ith != (hull.end() - 1))  
  79.     {  
  80.         line(result_erase, *ith, *(ith + 1), Scalar(128), 2);  
  81.         ++ith;  
  82.     }  
  83.     line(result_erase, *(hull.begin()), *(hull.end() - 1), Scalar(128), 2);  
  84.     //另一種強大的描述符力矩
  85.     //測試力矩
  86.     //遍歷所有輪廓
  87.     itc = contours.begin();  
  88.     while (itc!=contours.end())  
  89.     {  
  90.         //計算所有的力矩
  91.         Moments mom = moments(Mat(*itc++));  
  92.         //繪製質心
  93.         circle(result_erase,  
  94.             Point(mom.m10 / mom.m00, mom.m01 / mom.m00),    //質心座標轉換為整數
  95.             2,  
  96.             Scalar(0),  
  97.             2); //繪製黑點
  98.     }  
  99.     namedWindow("contours_erase");  
  100.     imshow("contours_erase", result_erase);  
  101.     waitKey(0);  
  102.     return 0;  
  103. }  

形狀描述符描述輪廓實驗結果