OpenCV库很强大,不仅能够显示图片,还能解码显示各种格式的视频文件,而且提供的API接口也很多,包括C、C++、Python。下面比较一下分别使用C和C++播放一段视频文件的实现:
C语言实现
$ cat test_video.c
#include
#include
#include
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
#include
using namespace std;
using namespace cv;
int main(void){
//打开视频文件
VideoCapture capture("./kakou.mp4");
//isOpen判断视频是否打开成功
if(!capture.isOpened())
{
cout<<"Movie open Error"< return -1; } //获取视频帧频 double rate=capture.get(CV_CAP_PROP_FPS); cout<<"帧率为:"<<" "< cout<<"总帧数为:"<<" "< 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