您的位置:首页 > 运维架构

OpenCV学习笔记三:视频读取

2017-03-09 20:05 375 查看

为了处理视频,需要读取视频的每一帧,OpenCV提供了一个非常易用的框架以读取视频文件或从摄像头中读取。

一、读取视频文件

读取视频文件,只需要创建VideoCapture实例,然后循环读取并处理每一帧就行了。

示例

#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

int main()
{
VideoCapture cap("1.mp4");
if(!cap.isOpened())//判断是否正确打开
return -1;
double frameRate = cap.get(CV_CAP_PROP_FPS);//获取视频FPS
Mat frame;
namedWindow("Video");
int delay = 1000/frameRate;
//循环读取,也可以用cap>>frame
while(cap.read(frame))
{
//Do anything you want to do
//这里将每一帧翻转
flip(frame,frame,-1);
imshow("Video",frame);
if(waitKey(delay)>=0)//设置延迟
break;
}
cap.release();
}


说明:

1、get方法用于查询视频信息,通过参数指定想要查询的信息。比如上例中通过CV_CAP_PROP_FPS获取帧率、视频文件的帧数是一个整数,可以这样获取

long frameCount = static_cast<long>(cap.get(CV_CAP_PROP_FRAME_COUNT));


还有其它一些信息比如

CV_CAP_PROP_POS_MSEC Current position of the video file in milliseconds.

CV_CAP_PROP_POS_FRAMES 0-based index of the frame to be decoded/captured next.

CV_CAP_PROP_POS_AVI_RATIO Relative position of the video file: 0 - start of the film, 1 - end of the film.

CV_CAP_PROP_FRAME_WIDTH Width of the frames in the video stream.

CV_CAP_PROP_FRAME_HEIGHT Height of the frames in the video stream.

CV_CAP_PROP_FOURCC 4-character code of codec.

CV_CAP_PROP_FORMAT Format of the Mat objects returned by retrieve() .

CV_CAP_PROP_MODE Backend-specific value indicating the current capture mode.

CV_CAP_PROP_BRIGHTNESS Brightness of the image (only for cameras).

CV_CAP_PROP_CONTRAST Contrast of the image (only for cameras).

CV_CAP_PROP_SATURATION Saturation of the image (only for cameras).

CV_CAP_PROP_HUE Hue of the image (only for cameras).

CV_CAP_PROP_GAIN Gain of the image (only for cameras).

CV_CAP_PROP_EXPOSURE Exposure (only for cameras).

CV_CAP_PROP_CONVERT_RGB Boolean flags indicating whether images should be converted to RGB.

CV_CAP_PROP_WHITE_BALANCE Currently unsupported

CV_CAP_PROP_RECTIFICATION Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend cur- rently)

……

相应地,可以用set函数可以设置其中的一些参数,比如通过CV_CAP_PROP_POS_FRAMES移动到特定的帧、用CV_CAP_PROP_MSEC移动到特定毫秒位置、CV_CAP_PROP_AVI_RATIO指定相对位置,0为开头,1为结尾。

2、通过指定delay可以控制视频播放速度

2、读取摄像头

从摄像头读取时,与读取文件相同,只是
9264
VideoCapture参数为设备索引号。对于笔记本内置摄像头而言,参数为0。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: