文章目录
- 一、读视频
-
- 1.打开视频文件
- 2.捕获摄像头
- 3.open()
- 4.读取到图像中
- 5.视频打开的例子
- 三、写视频
-
- 1.VideoWriter
- 2.函数
-
- (1)是否成功创建
- (2)写入
- 3.帧率fps
- 4.例子
一、读视频
1.打开视频文件
2.捕获摄像头
这个可能是
,也可能是
1
,
2
,
3
,
4
。一个个试试
3.open()
VideoCapture capture;
capture.open(0);
同
4.读取到图像中
直接重载操作符
>>
:
writer >> frame;
5.视频打开的例子
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat image;
VideoCapture capture;
capture.open(0);
if(capture.isOpened())
{
cout << "Capture is opened" << endl;
for(;;)
{
capture >> image;
if(image.empty())
break;
imshow("Sample", image);
if(waitKey(10) >= 0)
break;
}
}
else
{
cout << "No capture" << endl;
waitKey(0);
}
return 0;
}
三、写视频
1.VideoWriter
cv::VideoWriter::VideoWriter (
const String & filename,
int fourcc,
double fps,
Size frameSize,
bool isColor = true
)
- filename:如
xxx.avi
- fourcc:如
VideoWriter::fourcc('M', 'J', 'P', 'G')
- fps:帧率。意思是一秒有多少帧,决定一秒分配几个写入的帧。
- frameSize:
Size(图片的列宽,行高)
- isColor:不管了
2.函数
(1)是否成功创建
成功初始化返回true
(2)写入
或者直接重载操作符
<<
:
writer << frame;
3.帧率fps
每秒25帧

每秒1帧
4.例子
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
// 视频帧,图片行高400,列宽600
Mat frame(400, 600, CV_8UC3);
// 创建 writer,并指定 FOURCC、FPS和Size(图片的列宽,行高)
VideoWriter writer = VideoWriter("myvideo.avi", VideoWriter::fourcc('M', 'J', 'P', 'G'), 25, Size(frame.cols, frame.rows));
// 检查是否成功创建
if (!writer.isOpened())
{
cerr << "Can not create video file.\n";
return -1;
}
for (int i = 0; i < 100; i++)
{
// 将图像置为黑色
frame = Scalar::all(0);
// 将整数 i 转为 i 字符串类型
char text[128];
sprintf(text, "%d", i);
// 将数字绘到画面上
putText(frame, text, Point(200, 200), FONT_HERSHEY_SCRIPT_SIMPLEX, 3,
Scalar(0, 0, 255), 3);
// 将图像写入视频
writer << frame;
}
return 0;
}
opencv–读写视频