使用opencv显示视频的方法

  下面对使用opencv显示视频做一个简单的记录。当然,网上这方面的资料已经数不胜数了,我只是将其简单记录,总结一下。

  在opencv中显示视频主要有:

    (1)从本地读取视频和调用摄像头读取视频

    (2)使用C接口和使用C++接口

 

  一、使用opencv显示本地视频

    1、使用opencv的C++接口显示本地视频 

/*
 *使用opencv的C++接口显示本地视频
 */
#include <opencv2/highgui/highgui.hpp>  
#include <opencv2/imgproc/imgproc.hpp>  
#include <opencv2/core/core.hpp>

using namespace cv;
   
int main( int argc, char** argv )  
{  

    VideoCapture cap("test.mp4");  
    if(!cap.isOpened())  
    {  
        return -1;  
    }  
    Mat frame;   
    while(1)  
    {  
        cap>>frame;  
        if(frame.empty()) break;
        imshow("当前视频",frame);  
        if(waitKey(30) >=0)  
            break;
    }  
    return 0;
}

    

    2、使用opencv的C接口显示视频的test code

/*
 *使用opencv的C接口显示本地视频
 */
#include "highgui.h"
#include "cxcore.h"
#include "cv.h"
void main()
{
    cvNamedWindow("Example2", CV_WINDOW_AUTOSIZE);
    CvCapture* capture = cvCreateFileCapture("test.mp4");
    IplImage* frame;
    while(1) {
        frame = cvQueryFrame( capture );
        if( !frame ) break;
        cvShowImage( "Example2", frame );
        char c = cvWaitKey(33);
        if( c == 27 ) break;
    }
    cvReleaseCapture( &capture );
    cvDestroyWindow( "Example2" );
}

  二、使用opencv调用摄像头

    1、使用opencv的C++接口调用摄像头

/*
 *使用opencv的C++接口调用摄像头
 */


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

using namespace cv;
   
int main( int argc, char** argv )  
{  

    VideoCapture cap(0);  
    if(!cap.isOpened())  
    {  
        return -1;  
    }  
    Mat frame;   
    while(1)  
    {  
        cap>>frame;  
        if(frame.empty()) break;
        imshow("当前视频",frame);  
        if(waitKey(30) >=0)  
            break;
    }  
    return 0;
}

 

    2、使用opencv的C接口调用摄像头

/*
 *使用opencv的C接口调用摄像头
 */


#include "highgui.h"
#include "cxcore.h"
#include "cv.h"
void main()
{
    cvNamedWindow("Example2", CV_WINDOW_AUTOSIZE);
    CvCapture* capture = cvCreateCameraCapture(0);
    IplImage* frame;
    while(1) {
        frame = cvQueryFrame( capture );
        if( !frame ) break;
        cvShowImage( "Example2", frame );
        char c = cvWaitKey(33);
        if( c == 27 ) break;
    }
    cvReleaseCapture( &capture );
    cvDestroyWindow( "Example2" );
}

 

  三、总结

    1、使用C接口和使用C++接口需要包含不同的头文件

    2、C++接口用于保存视频信息的是VideoCapture,该数据接口提供两种构造函数VideoCapture(string &filename)和VideoCapture(int cameraNum)。以字符串为参数的构造函数用于显示本地视频,参数为视频路径。而以整型变量为参数的构造函数用于调用摄像头,参数代表调用的是第几个摄像头。

    3、C接口用于保存视频信息的是CvCapture结构体,并且通过函数cvCreateFileCapture(char * filename)来读取本地视频和通过cvCreateCameraCapture(int cameraNum)来调用摄像头。

    4、opencv中C和C++读取视频帧的方法也同相同,C通过cvQueryFrame函数来读取视频的下一帧并保存到IplImage结构体中,而C++接口直接通过">>"将视频的一帧读取出并保存到Mat结构体中。

 

posted @ 2015-09-11 09:50  Num.Zero  阅读(11553)  评论(0编辑  收藏  举报