houghlines.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include <cmath>
  2. #include <iostream>
  3. #include "opencv2/core.hpp"
  4. #include <opencv2/core/utility.hpp>
  5. #include "opencv2/highgui.hpp"
  6. #include "opencv2/imgproc.hpp"
  7. #include "opencv2/cudaimgproc.hpp"
  8. using namespace std;
  9. using namespace cv;
  10. using namespace cv::cuda;
  11. static void help()
  12. {
  13. cout << "This program demonstrates line finding with the Hough transform." << endl;
  14. cout << "Usage:" << endl;
  15. cout << "./gpu-example-houghlines <image_name>, Default is ../data/pic1.png\n" << endl;
  16. }
  17. int main(int argc, const char* argv[])
  18. {
  19. const string filename = argc >= 2 ? argv[1] : "../data/pic1.png";
  20. Mat src = imread(filename, IMREAD_GRAYSCALE);
  21. if (src.empty())
  22. {
  23. help();
  24. cout << "can not open " << filename << endl;
  25. return -1;
  26. }
  27. Mat mask;
  28. cv::Canny(src, mask, 100, 200, 3);
  29. Mat dst_cpu;
  30. cv::cvtColor(mask, dst_cpu, COLOR_GRAY2BGR);
  31. Mat dst_gpu = dst_cpu.clone();
  32. vector<Vec4i> lines_cpu;
  33. {
  34. const int64 start = getTickCount();
  35. cv::HoughLinesP(mask, lines_cpu, 1, CV_PI / 180, 50, 60, 5);
  36. const double timeSec = (getTickCount() - start) / getTickFrequency();
  37. cout << "CPU Time : " << timeSec * 1000 << " ms" << endl;
  38. cout << "CPU Found : " << lines_cpu.size() << endl;
  39. }
  40. for (size_t i = 0; i < lines_cpu.size(); ++i)
  41. {
  42. Vec4i l = lines_cpu[i];
  43. line(dst_cpu, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, LINE_AA);
  44. }
  45. GpuMat d_src(mask);
  46. GpuMat d_lines;
  47. {
  48. const int64 start = getTickCount();
  49. Ptr<cuda::HoughSegmentDetector> hough = cuda::createHoughSegmentDetector(1.0f, (float) (CV_PI / 180.0f), 50, 5);
  50. hough->detect(d_src, d_lines);
  51. const double timeSec = (getTickCount() - start) / getTickFrequency();
  52. cout << "GPU Time : " << timeSec * 1000 << " ms" << endl;
  53. cout << "GPU Found : " << d_lines.cols << endl;
  54. }
  55. vector<Vec4i> lines_gpu;
  56. if (!d_lines.empty())
  57. {
  58. lines_gpu.resize(d_lines.cols);
  59. Mat h_lines(1, d_lines.cols, CV_32SC4, &lines_gpu[0]);
  60. d_lines.download(h_lines);
  61. }
  62. for (size_t i = 0; i < lines_gpu.size(); ++i)
  63. {
  64. Vec4i l = lines_gpu[i];
  65. line(dst_gpu, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, LINE_AA);
  66. }
  67. imshow("source", src);
  68. imshow("detected lines [CPU]", dst_cpu);
  69. imshow("detected lines [GPU]", dst_gpu);
  70. waitKey();
  71. return 0;
  72. }