hough_lines.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include <opencv2/core/core.hpp>
  2. #include <opencv2/highgui/highgui.hpp>
  3. #include <opencv2/opencv.hpp>
  4. #include <stdio.h>
  5. #include <iostream>
  6. using namespace cv;
  7. using namespace std;
  8. // variables to store images
  9. Mat dst, cimg, gray, img, edges;
  10. int initThresh;
  11. const int maxThresh = 1000;
  12. double th1,th2;
  13. // create a vector to store points of line
  14. vector<Vec4i> lines;
  15. void onTrackbarChange( int , void* )
  16. {
  17. dst = img.clone();
  18. th1 = initThresh;
  19. th2 = th1 * 0.4;
  20. Canny(img,edges,th1,th2);
  21. // apply hough line transform
  22. HoughLinesP(edges, lines, 2, CV_PI/180, 50, 10, 100);
  23. // draw lines on the detected points
  24. for( size_t i = 0; i < lines.size(); i++ )
  25. {
  26. Vec4i l = lines[i];
  27. line( dst, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0,0,255), 1, LINE_AA);
  28. }
  29. // show the resultant image
  30. imshow("Result Image", dst);
  31. imshow("Edges", edges);
  32. }
  33. int main(int argc, char** argv) {
  34. const char* file = argv[1];
  35. // Read image (color mode)
  36. img = imread(file, 1);
  37. dst = img.clone();
  38. if(img.empty())
  39. {
  40. cout << "Error in reading image" << file<< endl;
  41. return -1;
  42. }
  43. // Convert to gray-scale
  44. cvtColor(img, gray, COLOR_BGR2GRAY);
  45. // Detect edges using Canny Edge Detector
  46. // Canny(gray, dst, 50, 200, 3);
  47. // Make a copy of original image
  48. // cimg = img.clone();
  49. // Will hold the results of the detection
  50. namedWindow("Edges",1);
  51. namedWindow("Result Image", 1);
  52. // Declare thresh to vary the max_radius of circles to be detected in hough transform
  53. initThresh = 500;
  54. // Create trackbar to change threshold values
  55. createTrackbar("threshold", "Result Image", &initThresh, maxThresh, onTrackbarChange);
  56. onTrackbarChange(initThresh, 0);
  57. while(true)
  58. {
  59. int key;
  60. key = waitKey( 1 );
  61. if( (char)key == 27 )
  62. { break; }
  63. }
  64. destroyAllWindows();
  65. }