videowriter_basic.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. @file videowriter_basic.cpp
  3. @brief A very basic sample for using VideoWriter and VideoCapture
  4. @author PkLab.net
  5. @date Aug 24, 2016
  6. */
  7. #include <opencv2/core.hpp>
  8. #include <opencv2/videoio.hpp>
  9. #include <opencv2/highgui.hpp>
  10. #include <iostream>
  11. #include <stdio.h>
  12. using namespace cv;
  13. using namespace std;
  14. int main(int, char**)
  15. {
  16. Mat src;
  17. // use default camera as video source
  18. VideoCapture cap(0);
  19. // check if we succeeded
  20. if (!cap.isOpened()) {
  21. cerr << "ERROR! Unable to open camera\n";
  22. return -1;
  23. }
  24. // get one frame from camera to know frame size and type
  25. cap >> src;
  26. // check if we succeeded
  27. if (src.empty()) {
  28. cerr << "ERROR! blank frame grabbed\n";
  29. return -1;
  30. }
  31. bool isColor = (src.type() == CV_8UC3);
  32. //--- INITIALIZE VIDEOWRITER
  33. VideoWriter writer;
  34. int codec = VideoWriter::fourcc('M', 'J', 'P', 'G'); // select desired codec (must be available at runtime)
  35. double fps = 25.0; // framerate of the created video stream
  36. string filename = "./live.avi"; // name of the output video file
  37. writer.open(filename, codec, fps, src.size(), isColor);
  38. // check if we succeeded
  39. if (!writer.isOpened()) {
  40. cerr << "Could not open the output video file for write\n";
  41. return -1;
  42. }
  43. //--- GRAB AND WRITE LOOP
  44. cout << "Writing videofile: " << filename << endl
  45. << "Press any key to terminate" << endl;
  46. for (;;)
  47. {
  48. // check if we succeeded
  49. if (!cap.read(src)) {
  50. cerr << "ERROR! blank frame grabbed\n";
  51. break;
  52. }
  53. // encode the frame into the videofile stream
  54. writer.write(src);
  55. // show live and wait for a key with timeout long enough to show images
  56. imshow("Live", src);
  57. if (waitKey(5) >= 0)
  58. break;
  59. }
  60. // the videofile will be closed and released automatically in VideoWriter destructor
  61. return 0;
  62. }