今天学习了opencv的摄像头调用,记录一下。
OpenCV中提供了专门操作视频的接口类VideoCapture,VideoCapture类可以从文件或者摄像设备中读取视频,提供常用的三种构造函数如下:
c++:VideoCapture:VideoCapture()
c++:VideoCapture:VideoCapture(const string& filename)
c++:VideoCapture:VideoCapture(int device)
参数说明:
实现视频类构造函数。参数filename表示输入视频文件的路径及名称;device表示打开视频操作索引号设置,如果是摄像头则设置device为0
打开本地视频,并显示帧数、像素宽、高。
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/imgproc/types_c.h>
#include <iostream>
void videoTest()
{
//定义VideoCapture对象
VideoCapture capture;
//读取视频文件【路径】
capture.open("E:\\shaky_car.avi");
//判断视频流读取是否正确
if (!capture.isOpened())
{
cout << "fail to open video" << endl;
return;
}
//获取视频相关信息-帧数
long nTotalFrame = capture.get(CAP_PROP_FRAME_COUNT);
cout << "nTotalFrame = " << nTotalFrame << endl;
//获取视频信息相关信息-帧像素宽、高
int frameHeight = capture.get(CAP_PROP_FRAME_HEIGHT);
int frameWidth = capture.get(CAP_PROP_FRAME_WIDTH);
cout << "frameHeight =" << frameHeight << endl;
cout << "frameWidth =" << frameWidth << endl;
//获取视频相关信息-帧率
double FrameRate = capture.get(CAP_PROP_FPS);
cout << "FrameRate =" << FrameRate << endl;
Mat frameImg; //用于存储读入的视频
//read方法获取显示帧
long nCount = 1;
while (true)
{
//输出当前帧号
cout << "Current frame" << nCount << endl;
capture >> frameImg; //读取当前帧
//判断当前读取文件
if (!frameImg.empty())
{
imshow("frameImg", frameImg); //显示
}
else
{
break;
}
//按下键盘Q退出
if (char(waitKey(1)) == 'q')
{
break;
}
nCount++;
}
capture.release(); //视频释放
}
int main(void)
{
videoTest();
system("pause");
return 0;
}
调用摄像头
void videoCameraTest()
{
//摄像头
VideoCapture capture(0);
/*
下面两句是设置摄像头的分辨率。不写这两句,则会显示默认分辨率:640*480
captureImage.set(CAP_PROP_FRAME_WIDTH, 320);
captureImage.set(CAP_PROP_FRAME_HEIGHT, 240);
现在是
capture.set(CAP_PROP_FRAME_HEIGHT, 240);
capture.set(CAP_PROP_FRAME_WIDTH, 320);
*/
capture.set(CAP_PROP_FRAME_HEIGHT, 240);
capture.set(CAP_PROP_FRAME_WIDTH, 320);
//判断视频流读取是否正确
if (!capture.isOpened())
{
cout << "fail to open video" << endl;
return;
}
//用于存储读入的图像
Mat frameImg;
while (true)
{
capture >> frameImg; //读取当前帧
//判断当前读取文件
if (!frameImg.empty())
{
imshow("frameImg", frameImg);
//转为灰度图像
Mat srcGray;
cvtColor(frameImg, srcGray, CV_RGB2GRAY);
imshow("srcGray", srcGray);
//均值平滑
Mat blurDstImage;
blur(srcGray, blurDstImage, Size(5, 5), Point(-1, -1));
imshow("blurDstImage", blurDstImage);
}
else
{
break;
}
//按下键盘Q退出
if (char(waitKey(1)) == 'q')
{
break;
}
}
//视频释放
capture.release();
}
然后在主函数调用videoCameraTest()
运行程序会出现三个界面,一个是原画面、一个是灰色图像、一个是模糊的。