呼叫opencv庫來讀取寫入視訊
語言:C++
視訊格式:MP4
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
int main()
{
cv::VideoCapture capture;
cv::Mat frame;
frame= capture.open("/Users/admin/Desktop/CodeBase/c++_try/1.mp4");// 視訊路徑
if(!capture.isOpened())
{
printf("can not open ...\n");
return -1;
}
while (capture.read(frame))
{
int width = frame.size().width;
int height = frame.size().height;
cv::imshow("origin", frame);
cv::waitKey(100);
}
capture.release();
return 0;
}
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
int main()
{
cv::VideoCapture capture;
cv::Mat frame;
frame= capture.open("/Users/admin/Desktop/CodeBase/c++_try/4.mp4");
double fps = capture.get(cv::CAP_PROP_FPS);
cv::VideoWriter writer("/Users/admin/Desktop/CodeBase/c++_try/out.mp4", cv::VideoWriter::fourcc('m','p','4','v'), fps, cv::Size(1280, 720));
if(!capture.isOpened())
{
printf("can not open ...\n");
return -1;
}
while (capture.read(frame))
{
int width = frame.size().width;
int height = frame.size().height;
writer << frame;
cv::imshow("origin", frame);
cv::waitKey(100);
}
capture.release();
return 0;
}
程式碼中有一句話,定義了一個cv::VideoWriter負責寫入視訊
cv::VideoWriter writer("/Users/admin/Desktop/CodeBase/c++_try/out.mp4", cv::VideoWriter::fourcc('m','p','4','v'), fps, cv::Size(1280, 720));
參數也好理解:路徑、編碼格式、影格率、影象大小
我找了一些資料:
cv::VideoWriter::fourcc(‘I’, ‘4’, ‘2’, ‘0’),該參數是YUV編碼型別,檔名後綴爲.avi
cv::VideoWriter::fourcc(‘P’, ‘I’, ‘M’, ‘I’),該參數是MPEG-1編碼型別,檔名後綴爲.avi
cv::VideoWriter::fourcc(‘X’, ‘V’, ‘I’, ‘D’),該參數是MPEG-4編碼型別,檔名後綴爲.avi
cv::VideoWriter::fourcc(‘T’, ‘H’, ‘E’, ‘O’),該參數是Ogg Vorbis,檔名後綴爲.ogv
cv::VideoWriter::fourcc(‘F’, ‘L’, ‘V’, ‘1’),該參數是Flash視訊,檔名後綴爲.flv
我還看到有人是這麼寫的
cv::VideoWriter::fourcc(‘M’, ‘J’, ‘P’, ‘G’),檔名後綴是.avi
在執行程式碼時,提示過幾次錯誤
OpenCV: FFMPEG: tag 0x00000898/'???' is not found (format 'avi / AVI (Audio Video Interleaved)
和
OpenCV: FFMPEG: tag 0x47504a4d/'MJPG' is not supported with codec id 7 and format 'mp4 / MP4
最後排查,都是上面提到的視訊編碼格式的問題cv::VideoWriter::fourcc
,寫程式碼時請注意你要的視訊後綴需要和編碼格式對應