C++获取电脑上连接的多个摄像头名称与编号

2018/07/07 15:29
阅读数 19

#include<iostream>
#include "strmif.h"
#include <initguid.h>
#include<vector>
#include<string>

#pragma comment(lib, "setupapi.lib")

using namespace std;

#define VI_MAX_CAMERAS 20
DEFINE_GUID(CLSID_SystemDeviceEnum, 0x62be5d10, 0x60eb, 0x11d0, 0xbd, 0x3b, 0x00, 0xa0, 0xc9, 0x11, 0xce, 0x86);
DEFINE_GUID(CLSID_VideoInputDeviceCategory, 0x860bb310, 0x5d01, 0x11d0, 0xbd, 0x3b, 0x00, 0xa0, 0xc9, 0x11, 0xce, 0x86);
DEFINE_GUID(IID_ICreateDevEnum, 0x29840822, 0x5b84, 0x11d0, 0xbd, 0x3b, 0x00, 0xa0, 0xc9, 0x11, 0xce, 0x86);

//列出硬件设备
int listDevices(vector<string>& list)
{
  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))
  {
    hr = pDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory,&pEnum, 0);
    if (hr == S_OK){

      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.
        }

        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 };
          while (varName.bstrVal[count] != 0x00 && count < 255)
          {
            tmp[count] = (char)varName.bstrVal[count];
            count++;
          }
          list.push_back(tmp);
        }

        pPropBag->Release();
        pPropBag = NULL;
        pMoniker->Release();
        pMoniker = NULL;

        deviceCounter++;
      }

      pDevEnum->Release();
      pDevEnum = NULL;
      pEnum->Release();
      pEnum = NULL;
    }
  }
  return deviceCounter;
}

 

int main()
{
  vector<string> CameraName;//存储摄像头名称
  int num = listDevices(CameraName);
  cout << "摄像头个数:" << num << endl;
  for (int i = 0; i < num; i++) {
    cout << " ID: "<< i << " : " << " Name: "<<CameraName[i] << endl;
  }

  //waitKey(0);
  system("pause");
  return 0;
}

 

 ===================运行效果===============

 

 代码复制粘贴即可运行

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部