1. 程式人生 > 實用技巧 >c++ opencv ffmpeg 圖片序列化視訊

c++ opencv ffmpeg 圖片序列化視訊

0、如果路徑中存在空格,用""把路徑包括起來

1、使用ffmpeg命令

ffmpeg -y -framerate 10 -start_number 1 -i E:\Image\Image_%d.bmp  E:\test.mp4
-y 			 表示輸出時覆蓋輸出目錄已存在的同名檔案
-framerate 10		 表示視訊幀率
-start_number 1		 表示圖片序號從1開始
-i E:\Image\Image_%d.bmp 表示圖片輸入流格式 

2、c++ 實現 ffmpeg命令

2.1、system方式

// 程式碼中執行過程中會出現黑屏的閃爍,無法隱藏
system("ffmpeg.exe -y -framerate 10 -start_number 1 -i E:\Image\Image_%d.bmp  E:\test.mp4");

2.2、ShellExecuteEx方式

SHELLEXECUTEINFO ShExecInfo = { 0 };
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;

ShExecInfo.lpVerb = L"open";
ShExecInfo.lpFile = L"ffmpeg.exe";
ShExecInfo.lpParameters = L"ffmpeg.exe -y -framerate 10 -start_number 1 -i E:\Image\Image_%d.bmp  E:\test.mp4";

ShExecInfo.lpDirectory = NULL;
ShExecInfo.nShow = SW_HIDE;//視窗狀態為隱藏
ShExecInfo.hInstApp = NULL;
if (ShellExecuteEx(&ShExecInfo))
{
    if (ShExecInfo.hProcess)
    {
        WaitForSingleObject(ShExecInfo.hProcess, INFINITE);
    }
}

3、使用opencv

cv::Mat image;
int fps = 10;//視訊幀率

/*cv::VideoWriter::fourcc('M', 'P', '4', 'V')生成MP4格式視訊*/
/*cv::VideoWriter::fourcc('M', 'J', 'P', 'G')生成avi格式視訊,大小比'X', 'V', 'I', 'D'大*/
/*cv::VideoWriter::fourcc('X', 'V', 'I', 'D')生成avi格式視訊*/
cv::VideoWriter writer("video_out.avi", cv::VideoWriter::fourcc('M', 'J', 'P', 'G'),
                       fps, cv::Size(3840, 2748)/*圖片大小,一定不能出錯*/, 0);

for (size_t i = 1; i <= 100; i++)
{
    image = cv::imread("Image_" + std::to_string(i) + ".bmp", cv::IMREAD_GRAYSCALE);
    if (!image.empty())
    {
        writer.write(image);
    }
}