1. Video loading (reading)/camera call uses the same function: VideoCapture()
Use the get function, such as video.get(CAP_PROP_FOURCC)
video real-time display and playback: video>>Mat
2. Video file save
3. Example: video reading and playback
Operation result: (GIF animation)
Attach example code:
#include<opencv2\opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int main()
{
VideoCapture video;
video.open("D:/opencv/风筝冲浪.mp4");
if (!video.isOpened())
{
cout << "请检查视频文件" << endl;
return -1;
}
cout <<"视频帧率=" << video.get(CAP_PROP_FPS) << endl;
cout <<"视频宽度=" << video.get(CAP_PROP_FRAME_WIDTH) << endl;
while (1)
{
Mat frame;
video >> frame;
if (frame.empty())
{
break;
}
imshow("video",frame);
uchar c = waitKey(1000 / video.get(CAP_PROP_FPS));//视频播放速度
if (c == 'q')
{
break; //按q键退出程序
}
}
return 0;
}
4. Example: camera call
Just change the path in the above example code to camera number: 0
Run result: (GIF animation)
5. Example: Save the image read by the camera or the processed video as a file again
Code:
#include<opencv2\opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int main()
{
Mat img;
VideoCapture video(0);//使用某个摄像头
//读取视频
//VideoCapture video;
//video.open("D:/opencv/风筝冲浪.mp4")
if (!video.isOpened())//判断是否调用成功
{
cout << "打开摄像头失败,请确认摄像头是否安装成功";
return -1;
}
video >> img;//获取图像
//检测是否成功获取图像
if (img.empty())//判断读取图像是否成功
{
cout << "没有获取到图像" << endl;
return -1;
}
bool isColor = {
img.type() == CV_8UC3 };//判断相机(视频)类型是否为彩色
VideoWriter writer;//定义写入视频的一个对象
int codec = VideoWriter::fourcc('M','J','P','G');//选择编码格式
//OpenCV 4.0版设置编码格式
//int codec=CV_FOURCC('M','J','P','G');
double fps = 25.0;//设置视频帧率
string filename = "newCamera.avi";//保存的视频文件名称
writer.open(filename, codec, fps, img.size(), isColor);//创建保存视频文件的视频流
if (!writer.isOpened())//判断视频流是否创建成功
{
cout << "打开视频文件失败,请确认是否为合法输入" << endl;
return -1;
}
while (1)
{
//检测是否执行完毕
if (!video.read(img))//判断能否继续从摄像头或者视频文件中读出一帧图像
{
cout << "摄像头断开连接或者视频读取完成" << endl;
break;
}
writer.write(img);//把图像写入视频流
//writer<<img;
imshow("newCamera",img);//显示图像
char c = waitKey(50);
if (c == 27)//按”Esc“键退出视频保存
{
break;
}
}
//退出程序时自动关闭视频流
//video.release();
//writer.release();
return 0;
}
Running result: (GIF animation)
Video file saved to: newCamera.avi