下面對使用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結構體中。