【OpenCV学习笔记 010】提取直线、轮廓及连通区域

一、Canny算子检测轮廓

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.  
  6. using namespace std;

  7. using namespace cv;

  8.  
  9. int main(){

  10.  
  11. Mat image = imread("tree.jpg", 0);

  12. namedWindow("image");

  13. imshow("image", image);

  14.  
  15. Mat contours;

  16. Canny(image, //灰度图

  17. contours, //输出轮廓

  18. 125, //低阈值

  19. 350); //高阈值

  20.  
  21. //因为正常情况下轮廓是用非零像素表示 我们反转黑白值

  22. Mat contoursInv; //反转后的图像

  23. threshold(contours,

  24. contoursInv,

  25. 128, //低于该值的像素

  26. 255, //将变成255

  27. THRESH_BINARY_INV);

  28. namedWindow("contoursInv");

  29. imshow("contoursInv", contoursInv);

  30.  
  31. waitKey(0);

  32. return 0;

  33. }

 

实验效果图

 

二、霍夫变换检测直线

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.  
  8. using namespace std;

  9. using namespace cv;

  10.  
  11. int main(){

  12.  
  13. Mat image = imread("tree.jpg");

  14. namedWindow("image");

  15. imshow("image", image);

  16.  
  17. Mat result;

  18. cvtColor(image, result, CV_BGR2GRAY);

  19. //应用Canny算法

  20. Mat contours;

  21. Canny(result, //灰度图

  22. contours, //输出轮廓

  23. 125, //低阈值

  24. 350); //高阈值

  25.  
  26. //Hough 变换检测直线

  27. vector <Vec2f>lines;

  28. HoughLines(contours, //一幅边缘图像

  29. lines, //代表检测到的浮点数

  30. 1,M_PI / 180, // 步进尺寸

  31. 80); //最小投票数

  32.  
  33. //绘制每条线

  34. vector<Vec2f>::const_iterator it = lines.begin();

  35. while (it!=lines.end())

  36. {

  37. float rho = (*it)[0]; //距离rho

  38. float theta = (*it)[1]; //角度theta

  39. if (theta<M_PI / 4. || theta>3.*M_PI / 4.) //垂直线

  40. {

  41. //线与第一行的交点

  42. Point pt1(rho / cos(theta), 0);

  43. //线与最后一行的交点

  44. Point pt2((rho - result.rows*sin(theta)) / cos(theta), result.rows);

  45. //绘制白线

  46. line(image, pt1, pt2, Scalar(255), 1);

  47. }

  48. else //水平线

  49. {

  50. //线与第一列的交点

  51. Point pt1(0, rho / sin(theta));

  52. //线与最后一列的交点

  53. Point pt2(result.cols, (rho - contours.cols*cos(theta)) / sin(theta));

  54. //绘制白线

  55. line(image, pt1, pt2, Scalar(255), 1);

  56. }

  57. ++it;

  58. }

  59.  
  60. cvNamedWindow("hough");

  61. imshow("hough", image);

  62. waitKey(0);

  63. return 0;

  64. }

程序运行结果

 

函数原型

 
  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.  
  8. using namespace std;

  9. using namespace cv;

  10.  
  11. class LineFinder{

  12.  
  13. private:

  14. Mat img; //原图

  15. vector<Vec4i>lines; //向量中检测到的直线的端点

  16. //累加器的分辨率

  17. double deltaRho;

  18. double deltaTheta;

  19. int minVote; //直线被接受时所需的最小投票数

  20. double minLength; //直线的最小长度

  21. double maxGap; //沿着直线方向的最大缺口

  22. public:

  23. //默认的累加器的分辨率为单个像素即1 不设置缺口及最小长度的值

  24. LineFinder() :deltaRho(1), deltaTheta(M_PI / 180), minVote(10), minLength(0.), maxGap(0.){};

  25.  
  26. //设置累加器的分辨率

  27. void setAccResolution(double dRho, double dTheta){

  28.  
  29. deltaRho = dRho;

  30. deltaTheta = dTheta;

  31. }

  32.  
  33. //设置最小投票数

  34. void setMinVote(int minv){

  35.  
  36. minVote = minv;

  37. }

  38.  
  39. //设置缺口及最小长度

  40. void setLineLengthAndGap(double length, double gap){

  41.  
  42. minLength = length;

  43. maxGap = gap;

  44. }

  45.  
  46. //使用概率霍夫变换

  47. vector<Vec4i>findLines(Mat &binary){

  48.  
  49. lines.clear();

  50. HoughLinesP(binary, lines, deltaRho, deltaTheta, minVote, minLength, maxGap);

  51. return lines;

  52. }

  53.  
  54. //绘制检测到的直线

  55. void drawDetectedLines(Mat &image,Scalar color = Scalar(255,255,255)){

  56.  
  57. //画线

  58. vector<Vec4i>::const_iterator it2 = lines.begin();

  59. while (it2!=lines.end())

  60. {

  61. Point pt1((*it2)[0],(*it2)[1]);

  62. Point pt2((*it2)[2], (*it2)[3]);

  63. line(image, pt1, pt2, color);

  64. ++it2;

  65. }

  66. }

  67. };

  68.  
  69. int main(){

  70.  
  71. Mat image = imread("tree.jpg");

  72. namedWindow("image");

  73. imshow("image", image);

  74.  
  75. Mat result;

  76. cvtColor(image, result, CV_BGR2GRAY);

  77. //应用Canny算法

  78. Mat contours;

  79. Canny(result, //灰度图

  80. contours, //输出轮廓

  81. 125, //低阈值

  82. 350); //高阈值

  83.  
  84. //创建LineFinder实例

  85. LineFinder finder;

  86. //设置概率Hough参数

  87. finder.setLineLengthAndGap(100, 20);

  88. finder.setMinVote(80);

  89. //检测并绘制直线

  90. vector<Vec4i>lines = finder.findLines(contours);

  91. finder.drawDetectedLines(image);

  92. cvNamedWindow("Detected Lines with HoughP");

  93. imshow("Detected Lines with HoughP", image);

  94. waitKey(0);

  95. return 0;

  96. }

测试结果

 

三、直线拟合一组点

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.  
  8. using namespace std;

  9. using namespace cv;

  10.  
  11. int main(){

  12.  
  13.     Mat image = imread("tree.jpg");

  14.     namedWindow("image");

  15.     imshow("image", image);

  16.  
  17.     Mat result;

  18.     cvtColor(image, result, CV_BGR2GRAY);

  19.     //应用Canny算法

  20.     Mat contours;

  21.     Canny(result,    //灰度图

  22.         contours,    //输出轮廓

  23.         125,    //低阈值

  24.         350);    //高阈值

  25.  
  26.     //创建LineFinder实例

  27.     LineFinder finder;

  28.     //设置概率Hough参数

  29.     finder.setLineLengthAndGap(100, 20);

  30.     finder.setMinVote(80);

  31.     //检测并绘制直线

  32.     vector<Vec4i>lines = finder.findLines(contours);

  33.  
  34.     int n = 0;    //选择line 0

  35.     //黑色图像

  36.     Mat oneline(contours.size(), CV_8U, Scalar(0));

  37.     //白色直线

  38.     line(oneline,

  39.         Point(lines[n][0], lines[n][1]),

  40.         Point(lines[n][2], lines[n][3]),

  41.         Scalar(255),

  42.         5

  43.         );

  44.  
  45.     //轮廓与白线进行AND操作

  46.     bitwise_and(contours, oneline, oneline);

  47.  
  48.     Mat oneLineInv;    //白色直线反转后的图像

  49.     threshold(oneline,

  50.         oneLineInv,

  51.         128,    //低于该值的像素

  52.         255,    //将变成255

  53.         THRESH_BINARY_INV);

  54.  
  55.     cvNamedWindow("One line");

  56.     imshow("One line", oneLineInv);

  57.  
  58.     //将指定直线相关的点置入cv::Points类型的std::vector中

  59.     vector<Point>points;

  60.     //遍历像素得到所有点的位置

  61.     for (int y = 0; y < oneline.rows; y++)

  62.     {

  63.         //y行

  64.         uchar *rowPtr = oneline.ptr<uchar>(y);

  65.         for (int x = 0; x < oneline.cols; x++)

  66.         {

  67.             //x列

  68.             //如果位于轮廓上

  69.             if (rowPtr[x])

  70.             {

  71.                 points.push_back(Point(x, y));

  72.             }

  73.         }

  74.     }

  75.  
  76.     Vec4f lineVec;

  77.     fitLine(Mat(points),

  78.         lineVec,

  79.         CV_DIST_L2,    //距离类型

  80.         0,    //L2距离不使用该参数

  81.         0.01,0.01);    //精确值

  82.  
  83.     int x0 = lineVec[2];    //直线上的点

  84.     int y0 = lineVec[3];

  85.     int x1 = x0 - 200 * lineVec[0];    //使用单元向量

  86.     int y1 = y0 - 200 * lineVec[1];    //添加长度为200的向量

  87.  
  88.     cv::line(result, Point(x0, y0), Point(x1, y1), Scalar(0), 3);

  89.  
  90.     cvNamedWindow("Estimated line");

  91.     imshow("Estimated line", result);

  92.     waitKey(0);

  93.     return 0;

  94. }

拟合效果图

 

实验过程说明

(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.  
  6. using namespace std;

  7. using namespace cv;

  8.  
  9. int main(){

  10.  
  11. Mat image = cvLoadImage("group.jpg");

  12. Mat grayImage;

  13. cvtColor(image, grayImage, CV_BGR2GRAY);

  14. //转换为二值图

  15. Mat binaryImage;

  16. threshold(grayImage, binaryImage, 90, 255, CV_THRESH_BINARY);

  17.  
  18. //二值图 这里进行了像素反转,因为一般我们用255白色表示前景(物体),用0黑色表示背景

  19. Mat reverseBinaryImage;

  20. bitwise_not(binaryImage, reverseBinaryImage);

  21.  
  22. vector <vector<Point>>contours;

  23. findContours(reverseBinaryImage,

  24. contours, //轮廓的数组

  25. CV_RETR_EXTERNAL, //获取外轮廓

  26. CV_CHAIN_APPROX_NONE); //获取每个轮廓的每个像素

  27. //在白色图像上绘制黑色轮廓

  28. Mat result(reverseBinaryImage.size(), CV_8U, Scalar(255));

  29. drawContours(result, contours,

  30. -1, //绘制所有轮廓

  31. Scalar(0), //颜色为黑色

  32. 2); //轮廓线的绘制宽度为2

  33.  
  34. namedWindow("contours");

  35. imshow("contours", result);

  36.  
  37. //移除过长或过短的轮廓

  38. int cmin = 100; //最小轮廓长度

  39. int cmax = 1000; //最大轮廓

  40. vector<vector<Point>>::const_iterator itc = contours.begin();

  41. while (itc!=contours.end())

  42. {

  43. if (itc->size() < cmin || itc->size() > cmax)

  44. itc = contours.erase(itc);

  45. else

  46. ++itc;

  47. }

  48.  
  49. //在白色图像上绘制黑色轮廓

  50. Mat result_erase(binaryImage.size(), CV_8U, Scalar(255));

  51. drawContours(result_erase, contours,

  52. -1, //绘制所有轮廓

  53. Scalar(0), //颜色为黑色

  54. 2); //轮廓线的绘制宽度为2

  55.  
  56. namedWindow("contours_erase");

  57. imshow("contours_erase", result_erase);

  58. waitKey(0);

  59. return 0;

  60. }

提取结果

 

五、计算连通区域的形状描述符

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.  
  6. using namespace std;

  7. using namespace cv;

  8.  
  9. int main(){

  10.  
  11. Mat image = cvLoadImage("group.jpg");

  12. Mat grayImage;

  13. cvtColor(image, grayImage, CV_BGR2GRAY);

  14. //转换为二值图

  15. Mat binaryImage;

  16. threshold(grayImage, binaryImage, 90, 255, CV_THRESH_BINARY);

  17.  
  18. //二值图 这里进行了像素反转,因为一般我们用255白色表示前景(物体),用0黑色表示背景

  19. Mat reverseBinaryImage;

  20. bitwise_not(binaryImage, reverseBinaryImage);

  21.  
  22. vector <vector<Point>>contours;

  23. findContours(reverseBinaryImage,

  24. contours, //轮廓的数组

  25. CV_RETR_EXTERNAL, //获取外轮廓

  26. CV_CHAIN_APPROX_NONE); //获取每个轮廓的每个像素

  27. //在白色图像上绘制黑色轮廓

  28. Mat result(reverseBinaryImage.size(), CV_8U, Scalar(255));

  29. drawContours(result, contours,

  30. -1, //绘制所有轮廓

  31. Scalar(0), //颜色为黑色

  32. 2); //轮廓线的绘制宽度为2

  33.  
  34. namedWindow("contours");

  35. imshow("contours", result);

  36.  
  37. //移除过长或过短的轮廓

  38. int cmin = 100; //最小轮廓长度

  39. int cmax = 1000; //最大轮廓

  40. vector<vector<Point>>::const_iterator itc = contours.begin();

  41. while (itc!=contours.end())

  42. {

  43. if (itc->size() < cmin || itc->size() > cmax)

  44. itc = contours.erase(itc);

  45. else

  46. ++itc;

  47. }

  48.  
  49. //在白色图像上绘制黑色轮廓

  50. Mat result_erase(binaryImage.size(), CV_8U, Scalar(255));

  51. drawContours(result_erase, contours,

  52. -1, //绘制所有轮廓

  53. Scalar(0), //颜色为黑色

  54. 2); //轮廓线的绘制宽度为2

  55.  
  56. //namedWindow("contours_erase");

  57. //imshow("contours_erase", result_erase);

  58.  
  59. //测试包围盒

  60. Rect r0 = boundingRect(Mat(contours[0]));

  61. rectangle(result_erase, r0, Scalar(128), 2);

  62. Rect r1 = boundingRect(Mat(contours[1]));

  63. rectangle(result_erase, r1, Scalar(128), 2);

  64.  
  65. //测试最小包围圆

  66. float radius;

  67. Point2f center;

  68. minEnclosingCircle(Mat(contours[2]), center, radius);

  69. circle(result_erase, Point(center), static_cast<int>(radius), Scalar(128), 2);

  70.  
  71. //测试多边形近似

  72. vector <Point> poly;

  73. approxPolyDP(Mat(contours[3]),

  74. poly,

  75. 5, //近似的精确度

  76. true); //这是个闭合形状

  77.  
  78. //遍历每个片段进行绘制

  79. vector<Point>::const_iterator itp = poly.begin();

  80. while (itp != (poly.end() - 1))

  81. {

  82. line(result_erase, *itp, *(itp + 1), Scalar(128), 2);

  83. ++itp;

  84. }

  85.  
  86. //首尾用直线相连

  87. line(result_erase, *(poly.begin()), *(poly.end() - 1), Scalar(128), 2);

  88.  
  89. //凸包是另一种多边形近似,计算凸包

  90. vector <Point> hull;

  91. convexHull(Mat(contours[4]), hull);

  92.  
  93. vector<Point>::const_iterator ith = hull.begin();

  94. while (ith != (hull.end() - 1))

  95. {

  96. line(result_erase, *ith, *(ith + 1), Scalar(128), 2);

  97. ++ith;

  98. }

  99. line(result_erase, *(hull.begin()), *(hull.end() - 1), Scalar(128), 2);

  100.  
  101. //另一种强大的描述符力矩

  102. //测试力矩

  103. //遍历所有轮廓

  104. itc = contours.begin();

  105. while (itc!=contours.end())

  106. {

  107. //计算所有的力矩

  108. Moments mom = moments(Mat(*itc++));

  109. //绘制质心

  110. circle(result_erase,

  111. Point(mom.m10 / mom.m00, mom.m01 / mom.m00), //质心坐标转换为整数

  112. 2,

  113. Scalar(0),

  114. 2); //绘制黑点

  115. }

  116.  
  117. namedWindow("contours_erase");

  118. imshow("contours_erase", result_erase);

  119. waitKey(0);

  120. return 0;

  121. }

 

形状描述符描述轮廓实验结果

 

【OpenCV学习笔记 010】提取直线、轮廓及连通区域 配套的源码下载

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值