ภาพรวม
สาธิตการ บันทึกวิดีโอ (Video Recording) จากกล้องเว็บแคม ลงไฟล์บนคอมพิวเตอร์ โดยใช้คลาส VideoWriter
พารามิเตอร์ VideoWriter
VideoWriter(filename, fourcc, fps, frameSize, isColor=true)
- filename: ชื่อไฟล์/พาธ (เช่น "video1.mp4")
- fourcc: 4-Character Code ระบุ Codec (เช่น MJPG, XVID, H264, MP4V)
- fps: เฟรมต่อวินาที
- frameSize: Size(width, height) ของเฟรม
- isColor: true = สี, false = Grayscale
โค้ดตัวอย่าง C++
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main() {
Mat myImage;
VideoCapture cap(0);
namedWindow("Video Player");
if (!cap.isOpened()) {
cout << "Failed to access camera" << endl;
system("pause");
return -1;
}
int frame_width = cap.get(CAP_PROP_FRAME_WIDTH);
int frame_height = cap.get(CAP_PROP_FRAME_HEIGHT);
// FourCC = 10 (MJPG), FPS = 17
VideoWriter video("video1.mp4", 10, 17, Size(frame_width, frame_height));
while (true) {
cap >> myImage;
if (myImage.empty()) break;
video.write(myImage); // เขียนเฟรมลงไฟล์
imshow("Video Player", myImage);
char c = (char)waitKey(25);
if (c == 27) break;
}
cap.release();
video.release();
return 0;
}
หมายเหตุสำคัญ
- FourCC Code ต้องรองรับโดยระบบ (Windows: MJPG=10, XVID=CV_FOURCC('X','V','I','D'))
- FPS และ Frame Size ต้องตรงกับกล้อง/อินพุต
- ต้อง
video.release()เพื่อ Flush Buffer และปิดไฟล์ให้สมบูรณ์ - บาง Codec ต้องติดตั้งเพิ่ม (เช่น H.264)
ผลลัพธ์
บันทึกไฟล์ "video1.mp4" ในโฟลเดอร์ทำงาน พร้อมแสดง Preview ระหว่างบันทึก