最近做项目遇到这个问题,因为要使用多像摄像头识别,所以要根据不同的摄像头设备打开指定设备。因为摄像头不同,要求要是区分摄像头,所以我这边采用摄像头设备号来区分。
实验环境: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;
}
完结。