美文网首页
使用OpenCV播放视频文件(C/C++ API比较)

使用OpenCV播放视频文件(C/C++ API比较)

作者: crazyhank | 来源:发表于2018-06-02 09:59 被阅读0次

    OpenCV库很强大,不仅能够显示图片,还能解码显示各种格式的视频文件,而且提供的API接口也很多,包括C、C++、Python。下面比较一下分别使用C和C++播放一段视频文件的实现:

    C语言实现

    $ cat test_video.c
    #include <opencv/cv.h>
    #include <opencv/highgui.h>
    #include <stdio.h>
    
    
    int main(int argc, char **argv)
    {
        CvCapture *cap;
        IplImage *frame;
    
        cap = cvCaptureFromFile("./kakou.mp4");
    
        printf("cap = %p\n", cap);
        while ((frame = cvQueryFrame(cap))) {
            //printf("frame = %p\n", frame);
            cvShowImage("MyTest", frame);
            cvWaitKey(33);
        }
    
        return 0;
    }
    $ gcc -o test_video test_video.c -lopencv_core  -lopencv_imgproc -lopencv_highgui
    

    C++语言实现

    $ cat test_video.cpp
    #include <iostream>
    #include <opencv/highgui.h>
    
    using namespace std;
    using namespace cv;
    int main(void){
    
        //打开视频文件
        VideoCapture capture("./kakou.mp4");
    
        //isOpen判断视频是否打开成功
        if(!capture.isOpened())
        {
            cout<<"Movie open Error"<<endl;
            return -1;
        }
        //获取视频帧频
        double rate=capture.get(CV_CAP_PROP_FPS);
        cout<<"帧率为:"<<" "<<rate<<endl;
        cout<<"总帧数为:"<<" "<<capture.get(CV_CAP_PROP_FRAME_COUNT)<<endl;//输出帧总数
        Mat frame;
        namedWindow("Movie Player");
    
        double position=0.0;
        //设置播放到哪一帧,这里设置为第0帧
        capture.set(CV_CAP_PROP_POS_FRAMES,position);
        while(1)
        {
            //读取视频帧
            if(!capture.read(frame))
                break;
    
            imshow("Movie Player",frame);
            //获取按键值
            char c=waitKey(33);
            if(c==27)
                break;
        }
        capture.release();
        destroyWindow("Movie Player");
        return 0;
    }
    $g++ -o test_video test_video.cpp -lopencv_core  -lopencv_imgproc -lopencv_highgui
    

    来一个效果图:

    image.png

    相关文章

      网友评论

          本文标题:使用OpenCV播放视频文件(C/C++ API比较)

          本文链接:https://www.haomeiwen.com/subject/mdolsftx.html