OpenCV+VS2019開啟和關閉電腦攝像頭
阿新 • • 發佈:2021-01-07
關於OpenCV和VS2019的配置,請參考部落格以前的連線。
OpenCV中主要使用videocapture來開啟和關閉攝像頭
https://docs.opencv.org/master/d8/dfe/classcv_1_1VideoCapture.html#afb4ab689e553ba2c8f0fec41b9344ae6
上述連線時OpenCV官網對於這個類的功能描述
定義
class cv::VideoCapture
建構函式,有三種
//功能:建立一個VideoCapture類的例項,如果傳入對應的引數,可以直接開啟視訊檔案或者要呼叫的攝像頭。 cv::VideoCapture::VideoCapture() cv::VideoCapture::VideoCapture(const String& filename, int apiPreference = CAP_ANY) //filename – 開啟的視訊檔名。 cv::VideoCapture::VideoCapture(int index,int apiPreference = CAP_ANY) //index – 開啟的視訊捕獲裝置id ,如果只有一個攝像頭可以填0,表示開啟預設的攝像。 //後面兩個引數可以不用管它
攝像頭開啟與關閉
virtual bool isOpened () const //視訊成功初始化,返回true
virtual bool open (const String &filename)//通過video capturing開啟視訊檔案或攝像頭
virtual bool open (int index) //通過攝像頭開啟視訊,預設為0,如果是帶前置攝像頭的電腦,一般為前置攝像頭。
但實際使用時,如下:
VideoCapture capture;//初始化一個VideoCapture例項,名字叫做capture capture.open("111.avi");//利用初始化的capture,開啟視訊"dog.avi" capture.open(0);//利用初始化的capture,開啟ID為0的攝像頭,一般有前置攝像頭的膝上型電腦,預設開啟該攝像頭。 capture.release();//關閉視訊檔案或者攝像頭
不過我建議使用最多的方式如下:
VideoCapture capture(0);//初始化一個VideoCapture例項,名字叫做capture,並開啟裝置0的攝像頭
讀取視訊幀
VideoCapture& VideoCapture::operator>>(Mat& image); bool VideoCapture::read(Mat& image);//該函式結合VideoCapture::grab()和VideoCapture::retrieve()其中之一被呼叫,用於捕獲、解碼和返回下一個視訊幀。假如沒有視訊幀被捕獲(相機沒有連線或者視訊檔案中沒有更多的幀)將返回false。
我建議使用如下方式:
Mat frame;//定義同一個mat變數,用來接收一幀影象
capture >> frame;//利用>>運算子,將capture的結果輸出到frame裡面去,就可以獲得幀影象
read和上述這種方式選一種即可,不要兩個都用
測試程式碼:
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int main()
{
VideoCapture capture(0);
int i=0;
//cin >> stop;
while(true) {
i++;
Mat frame;
capture >> frame;
imshow("讀取視訊",frame);
cout << i << endl;
if (i == 1000) {
capture.release();
break;
}
waitKey(30);
}
return 0;
}
程式碼中的i是為了能夠測試release函式關閉攝像頭