OpenCV指定pid和vid通过MSMF打开摄像头

在基于OpenCV的项目中,实际开发过程会面临设备上存在多个摄像头,需要指定摄像头的pid和vid打开摄像头。在OpenCV通过MSMF打开摄像头时,需要传入摄像头的index,因此需要在打开该摄像头前需要找出摄像头的index,下面给出通过微软的MF API找出MSMF枚举摄像头index的代码:

cpp 复制代码
#include <windows.h>
#include <mfapi.h>
#include <mfidl.h>
#include <mfreadwrite.h>
#include <string>
#include <vector>
#include <iostream>
#include <opencv2/opencv.hpp>

#pragma comment(lib, "mf.lib")
#pragma comment(lib, "mfplat.lib")
#pragma comment(lib, "mfreadwrite.lib")
#pragma comment(lib, "mfuuid.lib")

struct CameraInfo {
    int index;      // OpenCV 摄像头索引
    int vid;        // Vendor ID (e.g., 0x046D for Logitech)
    int pid;        // Product ID (e.g., 0x0825 for C920)
    std::string symbolicLink; // 设备符号链接
};

// 获取所有 Media Foundation 摄像头的 PID/VID
std::vector<CameraInfo> getMFCameraList() {
    std::vector<CameraInfo> cameras;

    IMFAttributes* pAttributes = nullptr;
    IMFActivate** ppDevices = nullptr;
    UINT32 count = 0;

    // 初始化 Media Foundation
    MFStartup(MF_VERSION);

    // 配置设备枚举参数(仅视频采集设备)
    MFCreateAttributes(&pAttributes, 1);
    pAttributes->SetGUID(
        MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
        MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID
    );

    // 枚举设备
    MFEnumDeviceSources(pAttributes, &ppDevices, &count);

    for (UINT32 i = 0; i < count; i++) {
        WCHAR* symbolicLink = nullptr;
        UINT32 length = 0;

        // 获取设备 Symbolic Link(包含 VID/PID)
        ppDevices[i]->GetAllocatedString(
            MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK,
            &symbolicLink,
            &length
        );

        if (symbolicLink) {
            std::wstring ws(symbolicLink);
            std::string devicePath(ws.begin(), ws.end());

            // 解析 VID/PID(格式:\\?\usb#vid_xxxx&pid_xxxx...)
            size_t vidPos = devicePath.find("vid_");
            size_t pidPos = devicePath.find("pid_");

            if (vidPos != std::string::npos && pidPos != std::string::npos) {
                std::string vidStr = devicePath.substr(vidPos + 4, 4);
                std::string pidStr = devicePath.substr(pidPos + 4, 4);

                int vid = std::stoi(vidStr, nullptr, 16);
                int pid = std::stoi(pidStr, nullptr, 16);

                cameras.push_back({-1, vid, pid, devicePath});
            }

            CoTaskMemFree(symbolicLink);
        }
        ppDevices[i]->Release();
    }

    if (pAttributes) pAttributes->Release();
    if (ppDevices) CoTaskMemFree(ppDevices);
    MFShutdown();

    return cameras;
}

// 匹配 OpenCV 摄像头索引
int findOpenCVCameraIndex(int targetVid, int targetPid) {
    auto cameras = getMFCameraList();
    int opencvIndex = 0;

    while (true) {
        cv::VideoCapture cap(opencvIndex, cv::CAP_MSMF);
        if (!cap.isOpened()) {
            break; // 没有更多摄像头
        }

        // 检查当前摄像头是否匹配目标 PID/VID
        for (const auto& cam : cameras) {
            if (cam.vid == targetVid && cam.pid == targetPid) {
                std::cout << "Found camera at OpenCV index: " << opencvIndex << std::endl;
                cap.release();
                return opencvIndex;
            }
        }

        cap.release();
        opencvIndex++;
    }

    return -1; // 未找到
}

int main() {
    // 示例:查找 Logitech C920(VID=0x046D, PID=0x0825)
    int targetVid = 0x046D;
    int targetPid = 0x0825;

    int cameraIndex = findOpenCVCameraIndex(targetVid, targetPid);
    if (cameraIndex != -1) {
        cv::VideoCapture cap(cameraIndex, cv::CAP_MSMF);
        if (cap.isOpened()) {
            std::cout << "Successfully opened target camera!" << std::endl;
            // 进行视频捕获...
        }
    } else {
        std::cerr << "Target camera not found." << std::endl;
    }

    return 0;
}
相关推荐
私人珍藏库2 小时前
[Android] PeakFinder AR v4.8.89 (山峰全景识别+增强现实山峰查看器)
android·人工智能·智能手机·ar·工具·软件
CS创新实验室3 小时前
算法、齿轮与硅基大脑:数值计算发展简史
人工智能·算法·数值计算
能有时光3 小时前
PyTorch KernelAgent 源码解读 ---(4)--- ExtractorAgent
人工智能·pytorch·python
fthux3 小时前
GitZip Pro 源码解析:一个 GitHub 文件/文件夹下载扩展是如何工作的(一)整体架构与扩展入口
人工智能·ai·开源·github·open source
aqi004 小时前
15天学会AI应用开发(十七)使用LangGraph实现会话记忆功能
人工智能·python·大模型·ai编程·ai应用
xixixi777774 小时前
三大 AI 安全里程碑:Akamai 高危风险预警、智能体水印强制落地、PQC 量子安全全产业链统一
大数据·人工智能·安全·ai·大模型·智能体·政策
AI小码5 小时前
LLM 应用的缓存工程:当每次 API 调用都在燃烧成本
java·人工智能·spring·计算机·llm·编程·api
code 小楊5 小时前
AI函数调用:Function Calling从理论到实战全解析
人工智能
delishcomcn5 小时前
智切未来:AI算法如何重塑不干胶标签分切机的精度与效率边界
人工智能·神经网络·计算机视觉
观远数据5 小时前
ChatBI选型对比:从意图识别到SQL修复,六个维度打分决定是否值得投产
数据库·人工智能·sql