video_writer.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include <iostream>
  2. #include "opencv2/opencv_modules.hpp"
  3. #if defined(HAVE_OPENCV_CUDACODEC)
  4. #include <vector>
  5. #include <numeric>
  6. #include "opencv2/core.hpp"
  7. #include "opencv2/cudacodec.hpp"
  8. #include "opencv2/highgui.hpp"
  9. using namespace cv;
  10. int main(int argc, const char* argv[])
  11. {
  12. if (argc != 2)
  13. {
  14. std::cerr << "Usage : video_writer <input video file>" << std::endl;
  15. return -1;
  16. }
  17. constexpr double fps = 25.0;
  18. cv::VideoCapture reader(argv[1]);
  19. if (!reader.isOpened())
  20. {
  21. std::cerr << "Can't open input video file" << std::endl;
  22. return -1;
  23. }
  24. cv::cuda::printShortCudaDeviceInfo(cv::cuda::getDevice());
  25. cv::VideoWriter writer;
  26. cv::Ptr<cv::cudacodec::VideoWriter> d_writer;
  27. cv::Mat frame;
  28. cv::cuda::GpuMat d_frame;
  29. cv::cuda::Stream stream;
  30. for (int i = 1;; ++i)
  31. {
  32. std::cout << "Read " << i << " frame" << std::endl;
  33. reader >> frame;
  34. if (frame.empty())
  35. {
  36. std::cout << "Stop" << std::endl;
  37. break;
  38. }
  39. if (!writer.isOpened())
  40. {
  41. std::cout << "Frame Size : " << frame.cols << "x" << frame.rows << std::endl;
  42. std::cout << "Open CPU Writer" << std::endl;
  43. const String outputFilename = "output_cpu.avi";
  44. if (!writer.open(outputFilename, cv::VideoWriter::fourcc('X', 'V', 'I', 'D'), fps, frame.size()))
  45. return -1;
  46. std::cout << "Writing to " << outputFilename << std::endl;
  47. }
  48. if (d_writer.empty())
  49. {
  50. std::cout << "Open CUDA Writer" << std::endl;
  51. const cv::String outputFilename = "output_gpu.h264";
  52. d_writer = cv::cudacodec::createVideoWriter(outputFilename, frame.size(), cv::cudacodec::Codec::H264, fps, cv::cudacodec::ColorFormat::BGR, 0, stream);
  53. std::cout << "Writing to " << outputFilename << std::endl;
  54. }
  55. d_frame.upload(frame, stream);
  56. std::cout << "Write " << i << " frame" << std::endl;
  57. writer.write(frame);
  58. d_writer->write(d_frame);
  59. }
  60. return 0;
  61. }
  62. #else
  63. int main()
  64. {
  65. std::cout << "OpenCV was built without CUDA Video encoding support\n" << std::endl;
  66. return 0;
  67. }
  68. #endif