OpenCV2学习(3)之读取视频文件以及读取摄像头

知识简述:视频就是一帧一帧的图片连接而成,因此无论是读取视频还是读取摄像头,都只是将视频流一帧一帧地输出!

读取视频文件:

//添加的头文件
#include <opencv2\opencv.hpp>  

//添加的命名空间
using namespace std;
using namespace cv;

//主程序
int main()
{
	int nCount = 1;

	//读入视频
	VideoCapture capture("F:/Image/123.mp4");
	cvNamedWindow("读取视频",0);

	//视频是否能打开
	if (!capture.isOpened())
	{
		cout << "Something wrong" << endl;
		system("pause");
		return -1;
	}

	//循环显示每一帧
	while (waitKey(30)!='q')//延时,并且检查循环条件
	{
		//定义一个Mat变量,用于存储每一帧的图像
		Mat frame;

		//读取当前帧
		capture >> frame; 

		//是否读完了
		if (!frame.empty())
		{
			//显示当前帧
			imshow("读取视频", frame);  
			cout << "Current frame is " << nCount << endl;
			nCount++;
		}
	}

	//释放
	capture.release();
	destroyAllWindows();

	return 0;
}

输出效果:

读取摄像头:

//添加的头文件
#include <opencv2\opencv.hpp>  

//添加的命名空间
using namespace std;
using namespace cv;

//主程序
int main()
{
	int nCount = 1;

	//读取摄像头
	VideoCapture capture(0);
	cvNamedWindow("摄像头",0);

	//摄像头是否能打开
	if (!capture.isOpened())
	{
		cout << "Something wrong" << endl;
		system("pause");
		return -1;
	}

	//循环显示每一帧
	while (waitKey(30)!='q')//延时,并且检查循环条件
	{
		//定义一个Mat变量,用于存储每一帧的图像
		Mat frame;

		//读取当前帧
		capture >> frame; 

		//是否读完了
		if (!frame.empty())
		{
			//显示当前帧
			imshow("摄像头", frame);  
			cout << "Current frame is " << nCount << endl;
			nCount++;
		}
	}

	//释放
	capture.release();
	destroyAllWindows();

	return 0;
}

效果图:

从上可得到,读取视频跟读取摄像头其实就是修改一个参数就可以了。

猜你喜欢

转载自blog.csdn.net/kou_ching/article/details/85348224