1 #include <iostream>
2
3 #include "opencv2/opencv_modules.hpp"
4
5 #if defined(HAVE_OPENCV_CUDACODEC) && defined(WIN32)
6
7 #include <vector>
8 #include <numeric>
9
10 #include "opencv2/core.hpp"
11 #include "opencv2/cudacodec.hpp"
12 #include "opencv2/highgui.hpp"
13
14 #include "tick_meter.hpp"
15
main(int argc,const char * argv[])16 int main(int argc, const char* argv[])
17 {
18 if (argc != 2)
19 {
20 std::cerr << "Usage : video_writer <input video file>" << std::endl;
21 return -1;
22 }
23
24 const double FPS = 25.0;
25
26 cv::VideoCapture reader(argv[1]);
27
28 if (!reader.isOpened())
29 {
30 std::cerr << "Can't open input video file" << std::endl;
31 return -1;
32 }
33
34 cv::cuda::printShortCudaDeviceInfo(cv::cuda::getDevice());
35
36 cv::VideoWriter writer;
37 cv::Ptr<cv::cudacodec::VideoWriter> d_writer;
38
39 cv::Mat frame;
40 cv::cuda::GpuMat d_frame;
41
42 std::vector<double> cpu_times;
43 std::vector<double> gpu_times;
44 TickMeter tm;
45
46 for (int i = 1;; ++i)
47 {
48 std::cout << "Read " << i << " frame" << std::endl;
49
50 reader >> frame;
51
52 if (frame.empty())
53 {
54 std::cout << "Stop" << std::endl;
55 break;
56 }
57
58 if (!writer.isOpened())
59 {
60 std::cout << "Frame Size : " << frame.cols << "x" << frame.rows << std::endl;
61
62 std::cout << "Open CPU Writer" << std::endl;
63
64 if (!writer.open("output_cpu.avi", cv::VideoWriter::fourcc('X', 'V', 'I', 'D'), FPS, frame.size()))
65 return -1;
66 }
67
68 if (d_writer.empty())
69 {
70 std::cout << "Open CUDA Writer" << std::endl;
71
72 const cv::String outputFilename = "output_gpu.avi";
73 d_writer = cv::cudacodec::createVideoWriter(outputFilename, frame.size(), FPS);
74 }
75
76 d_frame.upload(frame);
77
78 std::cout << "Write " << i << " frame" << std::endl;
79
80 tm.reset(); tm.start();
81 writer.write(frame);
82 tm.stop();
83 cpu_times.push_back(tm.getTimeMilli());
84
85 tm.reset(); tm.start();
86 d_writer->write(d_frame);
87 tm.stop();
88 gpu_times.push_back(tm.getTimeMilli());
89 }
90
91 std::cout << std::endl << "Results:" << std::endl;
92
93 std::sort(cpu_times.begin(), cpu_times.end());
94 std::sort(gpu_times.begin(), gpu_times.end());
95
96 double cpu_avg = std::accumulate(cpu_times.begin(), cpu_times.end(), 0.0) / cpu_times.size();
97 double gpu_avg = std::accumulate(gpu_times.begin(), gpu_times.end(), 0.0) / gpu_times.size();
98
99 std::cout << "CPU [XVID] : Avg : " << cpu_avg << " ms FPS : " << 1000.0 / cpu_avg << std::endl;
100 std::cout << "GPU [H264] : Avg : " << gpu_avg << " ms FPS : " << 1000.0 / gpu_avg << std::endl;
101
102 return 0;
103 }
104
105 #else
106
main()107 int main()
108 {
109 std::cout << "OpenCV was built without CUDA Video encoding support\n" << std::endl;
110 return 0;
111 }
112
113 #endif
114