houghlines.cpp 2.5 KB

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