>_<" 發現一個好的鏈接,是一個講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 }
