opencv第二章-显示一张图片和播放avi视频

opencv第二章-显示一张图片和播放avi视频


1)显示一张图片

#include <opencv2/opencv.hpp>  //头文件
using namespace cv;  //包含cv命名空间
void main( )
{    
// 【1】读入一张图片,载入图像
Mat srcImage = imread("1.jpg");
// 【2】显示载入的图片
imshow("【原始图】",srcImage);
// 【3】等待任意按键按下
waitKey(0);
}

(a)这是最新版的显示图片程序,省略了很多创建窗口和关闭窗口的程序。来看一下每句话的意思:

Mat srcImage = imread("1.jpg");//创建图像矩阵,矩阵元素为图像的像素,读入了图像。


(b)读入函数imread()的原型如下:

CV_EXPORTS_W Mat imread( const string& filename, int flags=1 )

第一个参数是文件路径,就是文件名,用双引号来表示文件名字符串

第二个参数是图像的大小,默认为1,就是原图。


(c)waitKye(0)的原型如下:

CV_EXPORTS_W int waitKey(int delay=0);

括号内的参数delay是表示要延时的时间,单位是ms毫秒。


(c)imshow()函数

CV_EXPORTS_W void imshow( const string& winname, InputArray mat );

第一个参数是要显示的窗口名称,用双引号来表示字符串

第二个参数是要显示的图像矩阵


2)老版本的程序如下:

int main()

{

IplImage *img=cvLoadImage("1.jpg");

cvNamedWindow("Example1",CV_WINDOW_AUTOSIZE);

cvShowImage("Example1",img);

cvWaitKey(0);

cvReleaseImage(&img);

cvDestroyWindow("Example1");

}


3)播放avi视频

#include <opencv2/opencv.hpp>  //头文件
using namespace cv;  //包含cv命名空间
int main( )
{    
//【1】读入视频
VideoCapture capture("1.avi");
//【2】循环显示每一帧
while(1)  
{  
Mat frame;//定义一个Mat变量,用于存储每一帧的图像
capture>>frame;  //读取当前帧
imshow("读取视频",frame);  //显示当前帧
waitKey(30);  //延时30ms
}  
return 0; 

使用opencv播放视频,几乎与使用它来显示图像一样容易,播放视频时只需要处理的新问题就是如何循环地顺序读取视频中的每一帧,以及如何从枯燥的电影视频的读取中退出该循环操作。我们先来看一下这个类VideoCapture。

(a)VideoCapture

class CV_EXPORTS_W VideoCapture
{
public:
    CV_WRAP VideoCapture();
    CV_WRAP VideoCapture(const string& filename);
    CV_WRAP VideoCapture(int device);
    
    virtual ~VideoCapture();
    CV_WRAP virtual bool open(const string& filename);
    CV_WRAP virtual bool open(int device);
    CV_WRAP virtual bool isOpened() const;
    CV_WRAP virtual void release();
    
    CV_WRAP virtual bool grab();
    CV_WRAP virtual bool retrieve(CV_OUT Mat& image, int channel=0);
    virtual VideoCapture& operator >> (CV_OUT Mat& image);
    CV_WRAP virtual bool read(CV_OUT Mat& image);
    
    CV_WRAP virtual bool set(int propId, double value);
    CV_WRAP virtual double get(int propId);
    
protected:
    Ptr<CvCapture> cap;
};

这个类里面有很多函数,用到哪个学哪个。

一般添加这个用来检测视频读取是否出错

if(!capture.isOpened())
{ cout<<"there is no this file";
exit(0);
}

如果出错,则输出出错信息,并退出程序。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值