先上DJ 先上DJ
先上代码
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main(int, char **)
{
Mat in_frame, out_frame;
const char win1[]="Grabbing...", win2[]="Recording...";
double fps=30;//每秒的帧数
char file_out[]="recorded.avi";
VideoCapture inVid("/dev/video0") ;
//打开摄像头,具体设备文件需先查看,参数为0,则为默认摄像头
if ( !inVid.isOpened())
{ //检查错误
cout << "Error! Camera not ready...\n";
return -1;
}
//获取输入视频的宽度和高度
int width = (int)inVid.get(CAP_PROP_FRAME_WIDTH);
int height = (int)inVid.get(CAP_PROP_FRAME_HEIGHT);
cout << "width = "<<width<<", height = "<<height<<endl;
VideoWriter recVid(file_out,VideoWriter::fourcc('X','V','I','D'), fps, Size(width, height),0);
if (!recVid.isOpened())
{
cout << "Error! Video file not opened...\n";
return -1;
}
//为原始视频和最终视频创建两个窗口
namedWindow(win1);
namedWindow(win2);
while (true)
{
//从摄像机读取帧(抓取并解码)以流的形式进行
inVid >> in_frame;
//将帧转换为灰度
cvtColor(in_frame, out_frame, COLOR_BGR2GRAY);
//将幀写入视频文件(编码并保存)以流的形式进行
recVid << out_frame;
imshow(win1, in_frame);// 在窗口中显示帧
imshow(win2, out_frame);// 在窗口中显示帧
if (waitKey(1000/fps) >= 0)
break;
}
inVid.release(); // 关闭摄像机
return 0;
}
cv::VideoCapture类
参数为const string&,即读入彩色图像,若设置为0则读取摄像头。
VideoCapture对象的操作可以像流一样读入到Mat类型的对象(即图像)中。
cv::VideoWriter类
这个类是用来写入一个视频的
构造函数 cv::VideoCapture(const string& path,int fourcc,double fps, Size framesize, bool isColor=true)
需要注意的是fourcc,cv::VideoWriter::fourcc(char c1,char c2,char c3,char c4)
常用的格式有
- CV_FOURCC('P','I','M','1') = MPEG-1 codec
- CV_FOURCC('M','J','P','G') = motion-jpeg codec
- CV_FOURCC('M', 'P', '4', '2') = MPEG-4.2 codec
- CV_FOURCC('D', 'I', 'V', '3') = MPEG-4.3 codec
- CV_FOURCC('D', 'I', 'V', 'X') = MPEG-4 codec
- CV_FOURCC('U', '2', '6', '3') = H263 codec
- CV_FOURCC('I', '2', '6', '3') = H263I codec
- CV_FOURCC('F', 'L', 'V', '1') = FLV1 codec
选择什么格式,需要依照具体的系统来确定,运行程序时报错可能就是这里的格式问题,见仁见智吧
成功运行之后,会生成一个recorded.avi文件,记录的是转换成灰色的视频


本文介绍了如何使用OpenCV的VideoCapture和VideoWriter类来读取视频并将其保存为灰度格式。重点讲解了VideoCapture的用法以及VideoWriter构造函数中的fourcc编码设置,包括常见编码格式,并提供了成功运行后的输出结果。

1716

被折叠的 条评论
为什么被折叠?



