Opencv识别设备ID 打开指定摄像头
Opencv中打开摄像头的语句是:
Videocapture cap;
cap.open(index);
Opencv中打开摄像头,当有多个摄像头时,有时候打开的不是想要的那个,因此有必要获得设备列表并选择合适的index。
跟踪源码,到cap_show.cpp中,在1293行发现了 int videoInput::listDevices(bool silent)函数。
把它单独摘出来,修改一下,即可获得设备列表。在此参考了https://blog.youkuaiyun.com/hyqwmxsh/article/details/74479694 这个链接。
int listDevices(vector& list) {
//COM Library Initialization
//comInit();
//if (!silent) DebugPrintOut("\nVIDEOINPUT SPY MODE!\n\n");
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;
}
完整测试工程可点此下载

当使用Opencv打开多个摄像头时,可能需要指定正确的设备ID。通过跟踪源码,可以找到videoInput::listDevices函数来获取设备列表,从而选择合适的index,确保打开的是目标摄像头。参考链接提供了实现这一功能的详细步骤。
5787

被折叠的 条评论
为什么被折叠?



