Merge pull request #8942 from zwsu:master
[platform/upstream/opencv.git] / samples / gpu / video_reader.cpp
1 #include <iostream>
2
3 #include "opencv2/opencv_modules.hpp"
4
5 #if defined(HAVE_OPENCV_CUDACODEC)
6
7 #include <string>
8 #include <vector>
9 #include <algorithm>
10 #include <numeric>
11
12 #include <opencv2/core.hpp>
13 #include <opencv2/core/opengl.hpp>
14 #include <opencv2/cudacodec.hpp>
15 #include <opencv2/highgui.hpp>
16
17 int main(int argc, const char* argv[])
18 {
19     if (argc != 2)
20         return -1;
21
22     const std::string fname(argv[1]);
23
24     cv::namedWindow("CPU", cv::WINDOW_NORMAL);
25     cv::namedWindow("GPU", cv::WINDOW_OPENGL);
26     cv::cuda::setGlDevice();
27
28     cv::Mat frame;
29     cv::VideoCapture reader(fname);
30
31     cv::cuda::GpuMat d_frame;
32     cv::Ptr<cv::cudacodec::VideoReader> d_reader = cv::cudacodec::createVideoReader(fname);
33
34     cv::TickMeter tm;
35     std::vector<double> cpu_times;
36     std::vector<double> gpu_times;
37
38     for (;;)
39     {
40         tm.reset(); tm.start();
41         if (!reader.read(frame))
42             break;
43         tm.stop();
44         cpu_times.push_back(tm.getTimeMilli());
45
46         tm.reset(); tm.start();
47         if (!d_reader->nextFrame(d_frame))
48             break;
49         tm.stop();
50         gpu_times.push_back(tm.getTimeMilli());
51
52         cv::imshow("CPU", frame);
53         cv::imshow("GPU", d_frame);
54
55         if (cv::waitKey(3) > 0)
56             break;
57     }
58
59     if (!cpu_times.empty() && !gpu_times.empty())
60     {
61         std::cout << std::endl << "Results:" << std::endl;
62
63         std::sort(cpu_times.begin(), cpu_times.end());
64         std::sort(gpu_times.begin(), gpu_times.end());
65
66         double cpu_avg = std::accumulate(cpu_times.begin(), cpu_times.end(), 0.0) / cpu_times.size();
67         double gpu_avg = std::accumulate(gpu_times.begin(), gpu_times.end(), 0.0) / gpu_times.size();
68
69         std::cout << "CPU : Avg : " << cpu_avg << " ms FPS : " << 1000.0 / cpu_avg << std::endl;
70         std::cout << "GPU : Avg : " << gpu_avg << " ms FPS : " << 1000.0 / gpu_avg << std::endl;
71     }
72
73     return 0;
74 }
75
76 #else
77
78 int main()
79 {
80     std::cout << "OpenCV was built without CUDA Video decoding support\n" << std::endl;
81     return 0;
82 }
83
84 #endif