OpenCV中VideoCapture类的使用详解

OpenCV中从视频文件或摄像机中捕获视频的类是VideoCapture。该类提供 C++ API 用于从摄像机捕获视频或读取视频文件。

关于视频的读操作是通过VideoCapture类来完成的;视频的写操作是通过VideoWriter类来实现的。

VideoCapture既支持从视频文件读取,也支持直接从摄像机(比如计算机自带摄像头)中读取。要想获取视频需要先创建一个VideoCapture对象,VideoCapture对象的创建方式有以下三种:

一、创建一个捕获对象,通过成员函数open()来设定打开的信息

#include
#include

using namespace cv;

int main()
{
	VideoCapture capture;
	Mat frame;
	frame = capture.open("video.mp4");
//	frame = capture.open("watershed.jpg");
	if (!capture.isOpened())
	{
		printf("can not open ...\n");
		return -1;
	}
	namedWindow("output", CV_WINDOW_AUTOSIZE);

	while (capture.read(frame))
	{
		imshow("output", frame);
		waitKey(60);
	}
	capture.release();
	return 0;
}

二、创建一个VideoCapture对象, 从摄像机中读取视频

#include
#include
using namespace cv;

int main()
{
	VideoCapture capture;
	capture.open(0);
	if (!capture.isOpened())
	{
		printf("can not open ...\n");
		return -1;
	}

	Size size = Size(capture.get(CV_CAP_PROP_FRAME_WIDTH), capture.get(CV_CAP_PROP_FRAME_HEIGHT));
	VideoWriter writer;
	writer.open("D:/image/a2.avi", CV_FOURCC('M', 'J', 'P', 'G'), 10, size, true);

	Mat frame, gray;
	namedWindow("output", CV_WINDOW_AUTOSIZE);

	while (capture.read(frame))
	{
		//转换为黑白图像
		cvtColor(frame, gray, COLOR_BGR2GRAY);
		//二值化处理 
	//	threshold(gray, gray, 0, 255, THRESH_BINARY | THRESH_OTSU);
		cvtColor(gray, gray, COLOR_GRAY2BGR);
	//	imshow("output", gray);
		imshow("output", frame);
		writer.write(gray);
		waitKey(10);
	}

	waitKey(0);
	capture.release();
	return 0;
}

三、从文件中读取视频

从文件中读取视频,对象创建以后,OpenCV将会打开文件并做好准备读取它,如果打开成功,将可以开始读取视频的帧,并且cv::VideoCapture的成员函数isOpened()将会返回true(建议在打开视频或摄像头时都使用该成员函数判断是否打开成功)

#include
#include

using namespace cv;

int main()
{
	VideoCapture capture;
	Mat frame;
	frame = capture("D:\\video.avi");
	if (!capture.isOpened())
	{
		printf("can not open ...\n");
		return -1;
	}
	namedWindow("output", CV_WINDOW_AUTOSIZE);

	while (capture.read(frame))
	{
		imshow("output", frame);
		waitKey(60);
	}
	capture.release();
	return 0;
}

总结:

OpenCV中里面成员函数多,要想获取视频需要先创建一个VideoCapture对象,可以先实例化再初始化,或者在实例化的同时进行初始化。

你可能感兴趣的:(C/C++,opencv,音视频,计算机视觉)