如何在计算机上使用 C++ 和 OpenCV 存储视频?


当我们要存储视频时,我们需要定义要存储视频的位置。之后我们需要指定 FourCC,FourCC 代表“四字符代码”。它是一连串 4 字节字符,用于识别数据格式。而且我们需要声明 FPS 来存储视频,帧大小对于此存储流程来说也是必要的。以下程序从默认摄像头获取实时视频流,并将视频存储在 C 目录中。

以下程序演示了如何在使用 C++ 和 OpenCV 的情况下,将视频存储在计算机中。

示例

#include<opencv2/opencv.hpp>//OpenCV header to use VideoCapture class and VideoWriter//
#include<iostream>
using namespace std;
using namespace cv;
int main() {
   Mat myImage;//Declaring a matrix to store the frames//
   VideoCapture cap(0);//Taking an object of VideoCapture Class to capture video from default camera//
   namedWindow("Video Player");//Declaring the video to show the video//
   if(!cap.isOpened()){ //This section prompt an error message if no video stream is found//
      cout << "Failed to access the camera" << endl;
      system("pause");
      return-1;
   }
   int frame_width = cap.get(CAP_PROP_FRAME_WIDTH);//Getting the frame height//
   int frame_height = cap.get(CAP_PROP_FRAME_HEIGHT);//Getting the frame width//
   VideoWriter video("video1.mp4",10,17,Size(frame_width, frame_height));//Declaring an object of VideoWriter class//
   while (true){ //Taking an everlasting loop to show the video//
      cap >> myImage;
      if (myImage.empty()){ //Breaking the loop if no video frame is detected//
         break;
      }
      video.write(myImage);//Write the video//
      imshow("Video Player", myImage);//Showing the video//
      char c= (char)waitKey(25);
      if(c==27){
         break;
      }
   }
   cap.release();//Releasing the buffer memory//
   video.release();
   return 0;
}

此程序会将视频以已定义的格式和名称存储在已定义的目录中。

更新于: 2021-03-10

564 浏览量

开启你的职业生涯

通过完成此课程获得认证

开始
广告
© . All rights reserved.