video_reader.cpp 2.3 KB

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