OpenCV之视频操作

一、读视频

1.打开视频文件

VideoCapture capture("1.avi");

2.捕获摄像头

这个可能是0,也可能是1234。一个个试试

VideoCapture capture(0);

3.open()

VideoCapture capture;
capture.open(0);

VideoCapture capture(0);

4.读取到图像中

直接重载操作符>>writer >> frame;

5.视频打开的例子

视频
打开成功提示后for循环
打开失败提示
帧为空退出
不空显示
按任意键退出
#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:帧率。意思是一秒有多少帧,决定一秒分配几个写入的帧。
  • frameSizeSize(图片的列宽,行高)
  • isColor:不管了

2.函数

(1)是否成功创建

bool cv::VideoWriter::isOpened	()

成功初始化返回true

(2)写入

void cv::VideoWriter::write(const Mat &image)

或者直接重载操作符<<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–读写视频

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值