[OpenCV] 3、直线提取 houghlines

 

>_<" 发现一个好的链接,是一个讲openCV的网站:http://www.opencv.org.cn/opencvdoc/2.3.2/html/index.html

>_<" 这次主要是houghlines变换来提取直线~

 1 #include "opencv2/highgui/highgui.hpp"
 2 #include "opencv2/imgproc/imgproc.hpp"
 3 #include <iostream>
 4 
 5 using namespace cv;
 6 using namespace std;
 7 
 8 int main(int argc, char** argv)
 9 {
10     const char* filename ="pic1.png";
11     Mat src = imread(filename, 0);
12 
13     Mat dst, cdst;
14     /*采用 Canny 算法做边缘检测
15     //void cvCanny( const CvArr* image, CvArr* edges, double threshold1,
16     //double threshold2, int aperture_size=3 );
17     //threshold1 第一个阈值 
18     //threshold2 第二个阈值 
19     //aperture_size Sobel 算子内核大小 (见 cvSobel). 
20     //函数 cvCanny 采用 CANNY 算法发现输入图像的边缘而且在输出图像中标识这些边缘。
21     //threshold1和threshold2 当中的小阈值用来控制边缘连接,大的阈值用来控制强边缘的初始分割。*/
22     Canny(src, dst, 50, 200, 3);
23     cvtColor(dst, cdst, CV_GRAY2BGR);//灰度化
24 #if 0
25     vector<Vec2f> lines;
26     /*利用 Hough 变换在二值图像中找到直线
27     CvSeq* cvHoughLines2( CvArr* image, void* line_storage, int method,
28                       double rho, double theta, int threshold,
29                       double param1=0, double param2=0 );
30     line_storage :检测到的线段存储仓. 
31     Hough 变换变量,是下面变量的其中之一: 
32         CV_HOUGH_STANDARD - 传统或标准 Hough 变换. 每一个线段由两个浮点数 (ρ, θ) 表示,
33             其中 ρ 是直线与原点 (0,0) 之间的距离,θ 线段与 x-轴之间的夹角。因此,矩阵类
34             型必须是 CV_32FC2 type. 
35         CV_HOUGH_PROBABILISTIC - 概率 Hough 变换(如果图像包含一些长的线性分割,则效率更高). 
36             它返回线段分割而不是整个线段。每个分割用起点和终点来表示,所以矩阵(或创建的序列)
37             类型是 CV_32SC4. 
38         CV_HOUGH_MULTI_SCALE - 传统 Hough 变换的多尺度变种。
39             线段的编码方式与 CV_HOUGH_STANDARD 的一致。 
40         rho 与象素相关单位的距离精度。
41         theta 弧度测量的角度精度。*/
42     HoughLines(dst, lines, 1, CV_PI/180, 100, 0, 0 );
43 
44     for( size_t i = 0; i < lines.size(); i++ )//将求得的线条画出来
45     {
46         float rho = lines[i][0], theta = lines[i][1];
47         Point pt1, pt2;
48         double a = cos(theta), b = sin(theta);
49         double x0 = a*rho, y0 = b*rho;
50         pt1.x = cvRound(x0 + 1000*(-b));
51         pt1.y = cvRound(y0 + 1000*(a));
52         pt2.x = cvRound(x0 - 1000*(-b));
53         pt2.y = cvRound(y0 - 1000*(a));
54         line( cdst, pt1, pt2, Scalar(0,0,255), 3, CV_AA);
55     }
56 #else
57     vector<Vec4i> lines;
58     HoughLinesP(dst, lines, 1, CV_PI/180, 50, 50, 10 );
59     for( size_t i = 0; i < lines.size(); i++ )
60     {
61         Vec4i l = lines[i];
62         line( cdst, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0,0,255), 3, CV_AA);
63     }
64 #endif
65     imshow("source", src);
66     imshow("detected lines", cdst);
67 
68     waitKey();
69 
70     return 0;
71 }

 

posted @ 2014-10-22 22:52  beautifulzzzz  阅读(12013)  评论(0编辑  收藏  举报