获取摄像头个数和名字

使用qt的QCameraInfo::availableCameras()一直获取到的摄像头个数都是0(本机上共有5个摄像头),使用qt自带的例子获取摄像头列表又获取得到,不知哪里出了问题。无奈只能网上查找。以下网址使用directshow获取摄像头个数和摄像头名字:里面的代码可下载来使用,只是里面有个包含的头文件#include 必须工程包含opencv的目录才能打开,否则编译不通过。但是单单获取摄像头个数和名称不需要用到这里面的这么多信息,因此单独取了这2个函数出来,如下关键代码处。

http://wiki.opencv.org.cn/index.php/使用DirectShow采集图像#.E5.8F.AF.E8.83.BD.E5.AD.98.E5.9C.A8.E7.9A.84.E7.BC.BA.E9.99.B7


关键代码为:

#pragma comment(lib,"Strmiids.lib") 
int CameraCount()
{
	int count = 0;
	CoInitialize(NULL);

	// enumerate all video capture devices
	CComPtr pCreateDevEnum;
	HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, (void**)&pCreateDevEnum);

	CComPtr pEm;
	hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pEm, 0);
	if (hr != NOERROR)
	{
		CoUninitialize();
		return count;
	}

	pEm->Reset();
	ULONG cFetched;
	IMoniker *pM;
	while (hr = pEm->Next(1, &pM, &cFetched), hr == S_OK)
	{
		count++;
	}

	pCreateDevEnum = NULL;
	pEm = NULL;
	CoUninitialize();
	return count;
}

int CameraName(int nCamID, char* sName, int nBufferSize)
{
	int count = 0;
	CoInitialize(NULL);

	// enumerate all video capture devices
	CComPtr pCreateDevEnum;
	HRESULT hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, (void**)&pCreateDevEnum);

	CComPtr pEm;
	hr = pCreateDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pEm, 0);
	if (hr != NOERROR) return 0;

	pEm->Reset();
	ULONG cFetched;
	IMoniker *pM;
	while (hr = pEm->Next(1, &pM, &cFetched), hr == S_OK)
	{
		if (count == nCamID)
		{
			IPropertyBag *pBag = 0;
			hr = pM->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pBag);
			if (SUCCEEDED(hr))
			{
				VARIANT var;
				var.vt = VT_BSTR;
				hr = pBag->Read(L"FriendlyName", &var, NULL); //还有其他属性,像描述信息等等...
				if (hr == NOERROR)
				{
					//获取设备名称			
					WideCharToMultiByte(CP_ACP, 0, var.bstrVal, -1, sName, nBufferSize, "", NULL);

					SysFreeString(var.bstrVal);
				}
				pBag->Release();
			}
			pM->Release();

			break;
		}
		count++;
	}

	pCreateDevEnum = NULL;
	pEm = NULL;
	CoUninitialize();
	return 1;
}


你可能感兴趣的:(获取摄像头个数和名字)