OpenCV视频文件读取;摄像头实时数据

网友投稿 1028 2022-05-30

视频或摄像头实时画面读取本质上是读取图像,因为视频是由一帧一帧图像组成的。

人们的眼睛在1秒24帧,就可以看成是连续的画面;这样基本能流畅的读取视频。

平常会用摄像头获取实时的画面数据;有时需要用摄像头记录保存一段画面数据;

那么又如何OpenCV来打开一段视频文件呢?

下面分为三个部分来分析,并附有原代码;

摄像头实时画面显示

思路流程:

定义一个Mat数据容器,等下用来存放摄像头的实时画面数据,使用 VideoCapture 函数来获取摄像头的实时画面数据;

把VideoCapture 函数读取到摄像头数据,写到Mat数据容器(frame),读取的是当前帧;

判断frame是否为空,如果不为空,用一个窗口(这里名字为window)显示摄像头的画面;

最后记得释放资源。

需要注意的是:VideoCapture capture(0)中,0默认是笔记本的摄像头;如果是外接摄像头,这里改为1。

在实时显示画面数据中,需要使用waitKey( )函数;不然摄像头的画面不会停留,直接不显示的;在下面程序是停留20ms;

如果是waitKey(0);相当于一直阻塞在一帧数据中;画面会停留在一个画面的。

源代码:

#include

using namespace cv;

using namespace std;

int main()

{

Mat frame;

VideoCapture capture(0);//读取视摄像头实时画面数据,0默认是笔记本的摄像头;如果是外接摄像头,这里改为1

while (true)

{

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

if(!frame.empty()){ //判断输入的视频帧是否为空的

imshow("window",frame); //在window窗口显示frame摄像头数据画面

}

if(waitKey(20) == 'q') //延时20ms,获取用户是否按键的情况,如果按下q,会推出程序

break;

}

capture.release(); //释放摄像头资源

destroyAllWindows(); //释放全部窗口

return 0;

}

升华:建议大家读取视频加异常判断 ,因为这样有利于追查报错原因

1)打开视频失败(各种原因)

if(!cap.isOpened()) //检查打开是否成功

return;

2)取帧失败异常(程序结尾判断)

cap>>frame;

if(!frame.empty()) //判断当前 帧是否为空

{

imshow(“video”, frame);

waitKey(30);

}

else break;

摄像头记录保存一段画面数据

OpenCV提供VideoWriter类写视频文件,类的构造函数可以指定文件名、播放帧率、帧尺寸、是否创建彩色视频。

先看看VideoWriter函数:

VideoWriter(filename, fourcc, fps, frameSize[, isColor])

参数解析:

第一个参数是要保存的文件的路径

fourcc 指定编码器

fps 要保存的视频的帧率

frameSize 要保存的文件的画面尺寸

isColor 指示是黑白画面还是彩色的画面

例如这样使用:VideoWriter writer("out.avi", CV_FOURCC('M', 'P', '4', '2'), 25.0,  (1920,1080), True)

fourcc 指定编码器有如下几种(正常是直接指定用哪一种编码器;如果填写为-1时,会弹出一个窗口给我们选择;)

CV_FOURCC('P', 'I', 'M', '1') = MPEG-1 code

CV_FOURCC('M', 'J', 'P', 'G') = motion-jpeg codec

CV_FOURCC('M', 'P', '4', '2') = MPEG-4.2 codec

CV_FOURCC('D', 'I', 'V', '3') = MPEG-4.3 codec

CV_FOURCC('D', 'I', 'V', 'X') = MPEG-4 codec

CV_FOURCC('U', '2', '6', '3') = H263 codec

CV_FOURCC('I', '2', '6', '3') = H263I codec

CV_FOURCC('F', 'L', 'V', '1') = FLV1 codec

代码实例:

#include

using namespace cv;

using namespace std;

int main()

{

Mat frame;

VideoCapture capture(0);//读取视摄像头实时画面数据,0默认是笔记本的摄像头;如果是外接摄像头,这里改为1

Size size0=Size(capture.get(CV_CAP_PROP_FRAME_WIDTH),capture.get(CV_CAP_PROP_FRAME_HEIGHT));

VideoWriter writer("out.avi",-1,capture.get(CV_CAP_PROP_FPS),size0,false);

//也可以以下形式

//VideoWriter writer;

//writer.open("out.avi", CV_FOURCC('X', 'V', 'I', 'D'),cap.get(CV_CAP_PROP_FPS),Size(cap.get(CV_CAP_PROP_FRAME_WIDTH),cap.get(CV_CAP_PROP_FRAME_HEIGHT)));

while (true)

{

capture >> frame;

if(!frame.empty()){ //判断输入的视频帧是否为空的

writer<

imshow("window",frame);

}

if(waitKey(20) == 'q') //延时20ms,获取用户是否按键的情况,如果按下q,会推出程序

break;

}

capture.release();

destroyAllWindows();

return 0;

}

注意:

1)写入视频前需安装对应的编解码器

2)生成视频是否支持彩色应与构造函数设置一致

3)生成视频尺寸需与读取视频尺寸一致

读取视频文件文件

源代码:

#include

#include

#include

int main(int argc, char* argv[])

{

cv::VideoCapture capture;

//capture.open(0); //打开摄像头

capture.open("1.mp4"); //打开视频

if (!capture.isOpened())

{

std::cout << "video not open." << std::endl;

return 1;

}

double rate = capture.get(CV_CAP_PROP_FPS); //获取当前视频帧率

//当前视频帧

cv::Mat frame;

//每一帧之间的延时

int delay = 1000/ rate; //与视频的帧率相对应

bool stop(false);

while (!stop)

{

if (!capture.read(frame)) //获取视频或摄像头的每一帧

{

std::cout << "no video frame" << std::endl;

break;

}

//此处为添加对视频的每一帧的操作方法

int frame_num = capture.get(CV_CAP_PROP_POS_FRAMES);

std::cout << "Frame Num : " << frame_num << std::endl;

if (frame_num == 500) //获取500帧

{

capture.set(CV_CAP_PROP_POS_FRAMES, 10); //重新设置帧数 重头播放

}

cv::imshow("video", frame);

//引入延时

//也可通过按键停止

if (cv::waitKey(delay)>0)

stop = true;

}

//关闭视频,手动调用析构函数(非必须)

capture.release();

return 0;

}

下面介绍一下原理:

VideoCapture  类

OpenCV 中通过 VideoCapture 类对视频进行读取操作以及调用摄像头。

VideoCapture 类提供常用的三种构造函数:

C++: VideoCapture::VideoCapture()

C++: VideoCapture::VideoCapture(const string& filename)

C++: VideoCapture::VideoCapture(int device)

功能:创建一个 VideoCapture 类的实例,如果传入对应的参数,可以直接打开视频文件

或者要调用的摄像头。其中参数:

(1)filename 为打开的视频文件名;

(2)device 为打开的视频捕获设备(即摄像头)id,如果只有一个摄像头可以填 0,表

示打开默认的摄像头。

VideoCapture 类 常用函数

(1)VideoCapture::open

Open 函数的功能是打开一个视频文件或者打开一个捕获视频的设备(即摄像头)

bool VideoCapture::open(const string& filename)

bool VideoCapture::open(int device)

其中参数:

  filename:打开的视频文件名。

  device:打开的视频捕获设备 id,如果只有一个摄像头可以填 0,表示打开默认的摄像头。

由上可知,OpenCV 读入视频的方法有两种,比如读取当前目录下名为"test.avi"的视频文件,如下:

//第一种方法:先实例化再初始化

VideoCapture capture;capture.open("test.avi");

//第二种方法:在实例化的同时进行初始化

VideoCapture capture("test.avi");

(2)VideoCapture::isOpened

C++: bool VideoCapture::isOpened()

功能:判断视频读取或者摄像头调用是否成功,成功则返回 true。

(3)VideoCapture::release

C++: void VideoCapture::release()

功能:关闭视频文件或者摄像头。

(4)VideoCapture::grab

C++: bool VideoCapture::grab()

功能:从视频文件或捕获设备中抓取下一个帧,假如调用成功返回 true。(细节请参考opencv 文档说明)

(5)VideoCapture::retrieve

C++: bool VideoCapture::retrieve(Mat& image, int channel=0)

功能:解码并且返回刚刚抓取的视频帧,假如没有视频帧被捕获(相机没有连接或者视频文件中没有更多的帧)将返回 false。

(6)VideoCapture::read

C++: VideoCapture& VideoCapture::operator>>(Mat& image)

C++: bool VideoCapture::read(Mat& image)

功能:该函数结合 VideoCapture::grab()和 VideoCapture::retrieve()其中之一被调用,用于捕获、解码和返回下一个视频帧。这是一个最方便的函数,对于读取视频文件或者捕获从解码和返回刚刚捕获的帧,假如没有视频帧被捕获(相机没有连接或者视频文件中没有更多的帧)将返回 false。

从上面的 API 中我们会发现获取视频帧可以有多种方法 :

// 方法一

capture.read(frame);

// 方法二

capture.grab();

// 方法三

capture.retrieve(frame);

// 方法四

capture >> frame;

(7)VideoCapture::get

C++: double VideoCapture::get(int propId)

功能:一个视频有很多属性,比如:帧率、总帧数、尺寸、格式等,VideoCapture 的 get方法可以获取这些属性。其中参数,即属性的 ID,属性的 ID 可以是下面的之一:

  CV_CAP_PROP_POS_MSEC Current position of the video file in milliseconds orvideo capture timestamp.

  CV_CAP_PROP_POS_FRAMES 0-based index of the frame to be decoded/capturednext.

  CV_CAP_PROP_POS_AVI_RATIO Relative position of the video file: 0 - start of thefilm, 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_FPS Frame rate.

  CV_CAP_PROP_FOURCC 4-character code of codec.

  CV_CAP_PROP_FRAME_COUNT Number of frames in the video file.

  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 not supported

  CV_CAP_PROP_RECTIFICATION Rectification flag for stereo cameras (note: only

supported by DC1394 v 2.x backend currently)

注意,如果查询的视频属性是 VideoCapture 类不支持的,将会返回 0。

(8)VideoCapture::set

C++: bool VideoCapture::set(int propertyId, double value)

功能:设置 VideoCapture 类的属性,设置成功返回 ture,失败返回 false。

参数:第一个是属性 ID,第二个是该属性要设置的值。属性 ID 如下:

  CV_CAP_PROP_POS_MSEC Current position of the video file in milliseconds.

OpenCV视频文件读取;摄像头实时数据

  CV_CAP_PROP_POS_FRAMES 0-based index of the frame to be decoded/capturednext.

  CV_CAP_PROP_POS_AVI_RATIO Relative position of the video file: 0 - start of thefilm, 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_FPS Frame rate.

  CV_CAP_PROP_FOURCC 4-character code of codec.

  CV_CAP_PROP_FRAME_COUNT Number of frames in the video file.

  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 beconverted to RGB.

  CV_CAP_PROP_WHITE_BALANCE Currently unsupported

  CV_CAP_PROP_RECTIFICATION Rectification flag for stereo cameras (note: onlysupported by DC1394 v 2.x backend currently)

可以谷歌翻译一下,具体的含义。

参考:opencv 视频中人脸检测

希望对你有帮助。

OpenCV 视频

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:excel表格升序降序的使用教程
下一篇:敏捷开发的7大指导原则
相关文章