opencv3多攝像頭情況下開啟指定攝像頭
阿新 • • 發佈:2021-01-13
最近做專案遇到這個問題,因為要使用多像攝像頭識別,所以要根據不同的攝像頭裝置開啟指定裝置。因為攝像頭不同,要求要是區分攝像頭,所以我這邊採用攝像頭裝置號來區分。
實驗環境:vs2013
opencv3.0
話不多說,上程式碼:
首先要是被到攝像頭的裝置號,根據裝置號可以追蹤到攝像頭的裝置id。
這是借鑑的另外一個部落格的。在此感謝。連結
int listDevices(vector<string>& list) {
//COM Library Initialization
//comInit();
ICreateDevEnum *pDevEnum = NULL;
IEnumMoniker *pEnum = NULL;
int deviceCounter = 0;
CoInitialize(NULL);
HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL,
CLSCTX_INPROC_SERVER, IID_ICreateDevEnum,
reinterpret_cast<void**>(&pDevEnum));
if (SUCCEEDED(hr))
{
// Create an enumerator for the video capture category.
hr = pDevEnum->CreateClassEnumerator(
CLSID_VideoInputDeviceCategory,
&pEnum, 0);
if (hr == S_OK) {
printf("SETUP: Looking For Capture Devices\n");
IMoniker *pMoniker = NULL;
while (pEnum->Next(1, &pMoniker, NULL) == S_OK) {
IPropertyBag *pPropBag;
hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag,
(void**)(&pPropBag));
if (FAILED(hr)) {
pMoniker->Release();
continue; // Skip this one, maybe the next one will work.
}
// Find the description or friendly name.
VARIANT varName;
VariantInit(&varName);
hr = pPropBag->Read(L"Description", &varName, 0);
if (FAILED(hr)) hr = pPropBag->Read(L"FriendlyName", &varName, 0);
if (SUCCEEDED(hr))
{
hr = pPropBag->Read(L"FriendlyName", &varName, 0);
int count = 0;
char tmp[255] = { 0 };
//int maxLen = sizeof(deviceNames[0]) / sizeof(deviceNames[0][0]) - 2;
while (varName.bstrVal[count] != 0x00 && count < 255)
{
tmp[count] = (char)varName.bstrVal[count];
count++;
}
list.push_back(tmp);
//deviceNames[deviceCounter][count] = 0;
//if (!silent) DebugPrintOut("SETUP: %i) %s\n", deviceCounter, deviceNames[deviceCounter]);
}
pPropBag->Release();
pPropBag = NULL;
pMoniker->Release();
pMoniker = NULL;
deviceCounter++;
}
pDevEnum->Release();
pDevEnum = NULL;
pEnum->Release();
pEnum = NULL;
}
//if (!silent) DebugPrintOut("SETUP: %i Device(s) found\n\n", deviceCounter);
}
//comUnInit();
return deviceCounter;
}
然後接下來就是要分別開啟指定攝像頭,讀取視訊流。
vector<string> list;
listDevices(list);
int capid0 = 0, capid1 = 0;
cout << "dev_size = " << list.size() << endl;
for (int i = 0; i<list.size(); i++)
{
if (list[i] == "Kinect V2 Video Sensor")
capid1 = i;
if (list[i] == "LRCP USB2.0")
capid0 = i;
cout << "device lists:" << list[i] << '\t' << "i=" << i << endl;
cout << capid1 << endl;
cout << capid0 << endl;
}
讀取到之後就進行開啟操作:
VideoCapture capture;
capture.open(capid0); //修改這個引數可以選擇開啟想要用的攝像頭,這裡我開啟的是"LRCP USB2.0")這個裝置,自己根據自己電腦識別出來的去修改
Mat frame;
while (true)
{
capture >> frame;
imshow("外接攝像頭", frame); //remember, imshow() needs a window name for its first parameter
if (waitKey(30) >= 0)
break;
}
完結。