linux opencv打开两个USB摄像头

本文介绍了在Ubuntu Linux系统中如何使用OpenCV打开和操作多个USB摄像头,重点讲解了如何通过/dev/videox设备节点识别真实和虚拟摄像头,并提供了代码示例。同时,还提供了一个根据设备vid和pid来选择特定摄像头的方法,确保正确打开目标摄像头。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在ubuntu linux系统下,摄像头设备是通过/dev/videox来表示的,如果只有一个摄像头,则会在/dev目录下显示 video0和video1两个设备,其中,video0是真实设备,而video1是一个虚拟设备。

1、多摄像头设备打开

当有两个USB摄像头时,会出现video0~video3 四个设备,其中video0和video2是真实设备,而video1和video3是虚拟设备,因此,只需要通过opencv打开video0和video2即可。通过opencv的VideoCapture打开多摄像头时,第一个设备video0对应的index为200,video2对应的index为200+2

代码如下:

int main() {
	VideoCapture cam1(200+2);
	VideoCapture cam0(200);
	while(true) {
		cv::Mat img0;
        cam0 >> img0;
        cv::Mat img1;
        cam1 >> img1;
        qDebug()<<img0.size << "   " <<img1.size;
	}
	return 0;
}
2、根据vid pid打开摄像头
int getUsbCameraVidPid(std::string devName, unsigned int &vid, unsigned int &pid)
{
    std::string str = devName;
    size_t pos = str.find_last_of("/");
    if (pos == std::string::npos) {
        fprintf(stderr, "  fail to get vid and pid\n");
        return -1;
    }
    std::string name = str.substr(pos+1);
    std::string modalias;
    vid = 0; pid = 0;
    if (!(std::ifstream("/sys/class/video4linux/" + name + "/device/modalias") >> modalias)) {
        return -1;
    }
    if (modalias.size() < 14 || modalias.substr(0,5) != "usb:v" || modalias[9] != 'p') {
        return -1;
    }
    if (!(std::istringstream(modalias.substr(5,4)) >> std::hex >> vid)) {
        return -1;
    }
    if (!(std::istringstream(modalias.substr(10,4)) >> std::hex >> pid)) {
        return -1;
    }

    fprintf(stdout, "  vid value: %d, pid value: %d\n", vid, pid);
    return  0;
}

int main() {
	int vid, int pid;
	// video2来作为例子,判断video2的pid
	std::string dev = "video2";
	int ret = getUsbCameraVidPid(dev, vid, pid);
	if (ret != 0) {
		return ret;
	}
	if (vid == 0x1234 && pid == 0x1212) { // check the pid and vid correct
		cv::Mat img;
		VideoCapture cam(200+2);
		while(true) {
			cv::Mat img;
	        cam >> img;
	        qDebug()<<img0.size << "   " <<img1.size;
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值