Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Cách lưu video lên máy tính trong OpenCV C++


Giới thiệu

Lưu video cần: đường dẫn file, FourCC (4 ký tự mã codec), FPS, kích thước frame. Dùng VideoWriter ghi từng frame.

Chương trình lưu video từ camera

#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 << "Không truy cập được 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' = 0x0000000A (thường dùng MJPG='MJPG', XVID='XVID', mp4v='mp4v')
    VideoWriter video("video1.mp4", VideoWriter::fourcc('m','p','4','v'), 17, Size(frame_width, frame_height));

    while (true) {
        cap >> myImage;
        if (myImage.empty()) break;
        video.write(myImage);
        imshow("Video Player", myImage);
        if (waitKey(25) == 27) break;
    }
    cap.release();
    video.release();
    return 0;
}

Kết quả

Video từ camera được lưu thành file video1.mp4 tại thư mục chạy chương trình.