如何在計算機上使用 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.