本次实验是检测图像中的直线,用到了HoughLines()和HoughLinesP()函数,其中HoughLinesP()称为累计概率霍夫变换,实验结果显示累计概率霍夫变换要比标准霍夫变换的效果好。具体的参数介绍书中网上都有,可参照此博客https://www.cnblogs.com/skyfsm/p/6881686.html
1 #include<opencv2/opencv.hpp> 2 #include<opencv2/imgproc/imgproc.hpp> 3 #include<iostream> 4 using namespace cv; 5 using namespace std; 6 7 Mat midImage, dstImage; // 临时变量和目标图的定义 8 void HoughLines_p(); 9 int main() 10 { 11 //载入原图 12 Mat src = imread("D:/bei1.jpg"); 13 namedWindow("原图", CV_WINDOW_AUTOSIZE); 14 imshow("原图", src); 15 //先进行边缘检测 在进行灰度变换 16 Canny(src, midImage, 50, 150, 3); 17 imwrite("D:/learn-opencv/can.jpg", midImage); 18 cvtColor(midImage, dstImage, CV_GRAY2BGR); 19 20 //进行霍夫线变换 21 vector<Vec2f>lines; //定义一个矢量结构lines用于存放得到的线段矢量集合 22 HoughLines(midImage, lines, 1, CV_PI / 180, 165, 0, 0); 23 24 //依次在图中做出每条线段 25 for (size_t i = 0; i < lines.size(); i++) 26 { 27 float r = lines[i][0]; 28 float theta = lines[i][1]; 29 30 Point pt1, pt2; 31 double a = cos(theta), b = sin(theta); 32 double x0 = a * r, y0 = b * r; 33 pt1.x = cvRound(x0 + 1000 * (-b)); 34 pt1.y = cvRound(y0 + 1000 * (a)); 35 pt2.x = cvRound(x0 - 1000 * (-b)); 36 pt2.y = cvRound(y0 - 1000 * (a)); 37 38 line(dstImage, pt1, pt2, Scalar(55, 100, 195), 1, LINE_AA); 39 } 40 41 //HoughLines_p();累积概率【霍夫变换】 42 imshow("边缘检测后的图", midImage); 43 imshow("显示效果图", dstImage); 44 imwrite("D:/learn-opencv/dstImage.jpg", dstImage); 45 waitKey(0); 46 return(0); 47 48 } 49 50 //累积概率【霍夫变换】 51 void HoughLines_p() 52 { 53 vector<Vec4i>lines; 54 HoughLinesP(midImage, lines, 1, CV_PI / 180, 80, 50, 10); 55 56 for (size_t i = 0; i < lines.size(); i++) 57 { 58 Vec4i l = lines[i]; 59 line(dstImage, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(186, 88, 255), 1, LINE_AA); 60 } 61 }
显示效果:
1.原图
2.canny边缘检测效果图
3.标准霍夫变换图
4.累计概率霍夫变换图