เมื่อเราต้องการจัดเก็บวิดีโอ เราต้องกำหนดตำแหน่งที่เราต้องการจัดเก็บ จากนั้นเราต้องระบุ FourCC FourCC ย่อมาจาก 'Four Character Code' เป็นลำดับของอักขระ 4 ไบต์ที่ระบุรูปแบบข้อมูล นอกจากนี้เรายังต้องประกาศ FPS เพื่อจัดเก็บวิดีโอและขนาดเฟรมก็จำเป็นสำหรับกระบวนการจัดเก็บนี้ โปรแกรมต่อไปนี้ใช้สตรีมวิดีโอแบบเรียลไทม์จากกล้องเริ่มต้นและจัดเก็บวิดีโอในไดเร็กทอรี C
โปรแกรมต่อไปนี้สาธิตวิธีจัดเก็บวิดีโอในคอมพิวเตอร์ของคุณใน OpenCV โดยใช้ C++
ตัวอย่าง
#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;
} โปรแกรมนี้จะจัดเก็บวิดีโอในไดเร็กทอรีที่กำหนดเป็นชื่อที่กำหนดไว้ในรูปแบบที่กำหนด