[OpenCV]獲取攝像頭視頻


環境:Windows 8 64bit + VS2012 X64 + OpenCV 2.4.7

攝像頭的捕捉使用VideoCapture類

Class VideoCapture    【OpenCV文檔的鏈接點這里

這個類專門用來從視頻文件或者攝像頭中獲取視頻流

具體的構造和相關方法,參考上面的官方文檔

示例代碼如下:

 1 #include "opencv2/opencv.hpp"
 2 
 3 using namespace cv;
 4 
 5 int main(int, char**)
 6 {
 7     VideoCapture cap(0); //打開默認的攝像頭號
 8     if(!cap.isOpened())  //檢測是否打開成功
 9         return -1;
10 
11     Mat edges;
12     namedWindow("edges",1);
13     for(;;)
14     {
15         Mat frame;
16         cap >> frame; // 從攝像頭中獲取新的一幀
17         cvtColor(frame, edges, CV_BGR2GRAY);
18         GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
19         Canny(edges, edges, 0, 30, 3);
20         imshow("edges", edges);
21         if(waitKey(30) >= 0) break;
22     }
23     //攝像頭會在VideoCapture的析構函數中釋放
24     return 0;
25 }

Get和Set方法的參數如下

C++: bool VideoCapture::set(int propId, double value) 和 double VideoCapture::get(int propId)

參數propId如下: 來自這里

CV_CAP_PROP_POS_MSEC 視頻當前點的毫秒值或視頻捕捉的時間戳
CV_CAP_PROP_POS_FRAMES 下次將被捕獲的0基索引的幀
CV_CAP_PROP_POS_AVI_RATIO 視頻文件的相關位置: 0 - start of the film, 1 - end of the film.
CV_CAP_PROP_FRAME_WIDTH 視頻流幀的寬度
CV_CAP_PROP_FRAME_HEIGHT 視頻流幀的高.
CV_CAP_PROP_FPS 幀率.
CV_CAP_PROP_FOURCC 4字符編碼的編碼器.
CV_CAP_PROP_FRAME_COUNT 視頻文件的幀數.
CV_CAP_PROP_FORMAT 由retrieve()返回矩陣對象的格式 .
CV_CAP_PROP_MODE 后端指定值指示當前捕捉的模式.
CV_CAP_PROP_BRIGHTNESS 圖像亮度 (只對攝像頭).
CV_CAP_PROP_CONTRAST 圖像對比度 (only for cameras).
CV_CAP_PROP_SATURATION 圖像飽和度 (only for cameras).
CV_CAP_PROP_HUE 色調 (only for cameras).
CV_CAP_PROP_GAIN 增益(only for cameras).
CV_CAP_PROP_EXPOSURE 曝光(only for cameras).
CV_CAP_PROP_CONVERT_RGB 布爾型標記圖像是否應該被轉換為RGB.
CV_CAP_PROP_WHITE_BALANCE 白平衡(目前不支持)
CV_CAP_PROP_RECTIFICATION 立體相機的矯正標記(note: only supported by DC1394 v 2.x backend currently)

 

在使用示例代碼的時候出現了個問題,在cap>>frame這里,獲取出現frame為空,但也有可以正常運行的。表示對底層的機制不了解,先拿來跑起來好了。

在stackoverflow上有人也問了這個問題,請點擊這里

有人說的原因是在VideoCapture剛開始獲取攝像頭視頻流的過程不返回信號,所以判斷Mat是否為空,並不斷循環去獲取Mat

把waitKey當做延時函數來更新窗口中獲取的圖像

 1   int cameraNumber = 0;
 2 
 3     VideoCapture camera;
 4     camera.open(cameraNumber);
 5     if ( !camera.isOpened() ) {
 6         cerr << "ERROR: Could not access the camera or video!" << endl;
 7         exit(1);
 8     }
 9 
10     int CAMERA_CHECK_ITERATIONS = 10;
11     while (true) {
12         Mat cameraFrame;
13         camera >> cameraFrame;   
14         if ( !cameraFrame.empty() ) {
15             imshow("Video", cameraFrame);
16             int key = waitKey(1);
17             if ( key == 27 )    break;
18         } else {
19             cout << "::: Accessing camera :::" << endl;
20             if ( CAMERA_CHECK_ITERATIONS > 0 ) CAMERA_CHECK_ITERATIONS--;
21             else  break;
22          }
23     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM