1 /**
2 * @file houghlines.cpp
3 * @brief This program demonstrates line finding with the Hough transform
4 */
5
6 #include "opencv2/imgcodecs.hpp"
7 #include "opencv2/highgui.hpp"
8 #include "opencv2/imgproc.hpp"
9
10 using namespace cv;
11 using namespace std;
12
main(int argc,char ** argv)13 int main(int argc, char** argv)
14 {
15 // Declare the output variables
16 Mat dst, cdst, cdstP;
17
18 //![load]
19 const char* default_file = "sudoku.png";
20 const char* filename = argc >=2 ? argv[1] : default_file;
21
22 // Loads an image
23 Mat src = imread( samples::findFile( filename ), IMREAD_GRAYSCALE );
24
25 // Check if image is loaded fine
26 if(src.empty()){
27 printf(" Error opening image\n");
28 printf(" Program Arguments: [image_name -- default %s] \n", default_file);
29 return -1;
30 }
31 //![load]
32
33 //![edge_detection]
34 // Edge detection
35 Canny(src, dst, 50, 200, 3);
36 //![edge_detection]
37
38 // Copy edges to the images that will display the results in BGR
39 cvtColor(dst, cdst, COLOR_GRAY2BGR);
40 cdstP = cdst.clone();
41
42 //![hough_lines]
43 // Standard Hough Line Transform
44 vector<Vec2f> lines; // will hold the results of the detection
45 HoughLines(dst, lines, 1, CV_PI/180, 150, 0, 0 ); // runs the actual detection
46 //![hough_lines]
47 //![draw_lines]
48 // Draw the lines
49 for( size_t i = 0; i < lines.size(); i++ )
50 {
51 float rho = lines[i][0], theta = lines[i][1];
52 Point pt1, pt2;
53 double a = cos(theta), b = sin(theta);
54 double x0 = a*rho, y0 = b*rho;
55 pt1.x = cvRound(x0 + 1000*(-b));
56 pt1.y = cvRound(y0 + 1000*(a));
57 pt2.x = cvRound(x0 - 1000*(-b));
58 pt2.y = cvRound(y0 - 1000*(a));
59 line( cdst, pt1, pt2, Scalar(0,0,255), 3, LINE_AA);
60 }
61 //![draw_lines]
62
63 //![hough_lines_p]
64 // Probabilistic Line Transform
65 vector<Vec4i> linesP; // will hold the results of the detection
66 HoughLinesP(dst, linesP, 1, CV_PI/180, 50, 50, 10 ); // runs the actual detection
67 //![hough_lines_p]
68 //![draw_lines_p]
69 // Draw the lines
70 for( size_t i = 0; i < linesP.size(); i++ )
71 {
72 Vec4i l = linesP[i];
73 line( cdstP, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0,0,255), 3, LINE_AA);
74 }
75 //![draw_lines_p]
76
77 //![imshow]
78 // Show results
79 imshow("Source", src);
80 imshow("Detected Lines (in red) - Standard Hough Line Transform", cdst);
81 imshow("Detected Lines (in red) - Probabilistic Line Transform", cdstP);
82 //![imshow]
83
84 //![exit]
85 // Wait and Exit
86 waitKey();
87 return 0;
88 //![exit]
89 }
90