基本思想:项目中需要动态获取外设红外设备的编号,进行视频流进行检测和处理
代码:
#include<opencv2/objdetect/objdetect.hpp>
#include<opencv2/highgui/highgui.hpp>
#include "windows.h"
#include "dshow.h"
#include <iostream>
#pragma comment(lib, "strmiids.lib")
#pragma comment(lib, "quartz.lib")
using namespace cv;
using namespace std;
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;
}
int main()
{
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] == "HD Pro Webcam C920")
capid0 = i;
if (list[i] == "S0-40")
capid1 = i;
cout << "device lists:" << list[i] << '\t' << "i=" << i << endl;
}
return 0;
}
测试结果
SETUP: Looking For Capture Devices
dev_size = 2
device lists:HD Pro Webcam C920 i=0
device lists:S0-40 i=1
F:\sxj\20200107\detectPhone\Project1\x64\Release\Project1.exe (进程 29892)已退出,代码为 0。
转载:OpenCV获取摄像头编号及名称_Yancy_的博客-_opencv usb摄像头 序号