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