前情提要:
因为实验室有一个任务需要同时使用两个免驱相机完成,opencv打开相机后发现一个致命的问题,每次插拔相机,会导致相机开启的那个id变化(0和2对换)
在csdn上找到了这样一篇文章:
Ubuntu18.04 系统下多个USB摄像头名称绑定,固定电脑主机USB端口名,用于解决同一型号的摄像头_CV_51154380的博客-CSDN博客_ubuntu修改usb摄像头名称
写的很好,但是有些地方有一些错误,或者不是很好理解,实际操作成功后,在此写一篇文章便于其他有同样问题的小伙伴查阅。
1.首先在终端输入
lsusb
得到结果(示例):
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 021: ID 0c45:6372 Microdia
Bus 001 Device 020: ID 0c45:6371 Microdia
Bus 001 Device 003: ID 046d:c539 Logitech, Inc.
Bus 001 Device 006: ID 8087:0aaa Intel Corp.
Bus 001 Device 002: ID 25a7:fa70
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
注:拔掉某一个再输入,看少了哪一个,就知道是谁了
2.接下来在终端输入:(以video0为例,video1,2,3同理)
udevadm info --attribute-walk --name=/dev/video0
Udevadm info starts with the device specified by the devpath and then
walks up the chain of parent devices. It prints for every device
found, all possible attributes in the udev rules key format.
A rule to match, can be composed by the attributes of the device
and the attributes from one single parent device.looking at device '/devices/pci0000:00/0000:00:14.0/usb1/1-3/1-3:1.0/video4linux/video0':
KERNEL=="video0"
SUBSYSTEM=="video4linux"
DRIVER==""
ATTR{dev_debug}=="0"
ATTR{index}=="0"
ATTR{name}=="LRCP HD60fps-01: LRCP HD60fps-0"
比如video2
looking at device '/devices/pci0000:00/0000:00:14.0/usb1/1-4/1-4:1.0/video4linux/video2':
KERNEL=="video2"
SUBSYSTEM=="video4linux"
DRIVER==""
ATTR{dev_debug}=="0"
ATTR{index}=="0"
ATTR{name}=="LRCP HD60fps-02: LRCP HD60fps-0"
从这里我们得到的信息是:
名字为LRCP HD60fps-01的相机是video0端口
名字为LRCP HD60fps-02的相机是video2端口
3.编辑新的rules
在终端输入:
sudo vi /etc/udev/rules.d/VIDEO.rules
编辑内容如下:
KERNEL=="video*",KERNELS=="1-4", ATTRS{idVendor}=="0c45", ATTRS{idProduct}=="6372",ATTR{index}=="0" , MODE:="0777", SYMLINK+="cam-2" KERNEL=="video*",KERNELS=="1-3", ATTRS{idVendor}=="0c45", ATTRS{idProduct}=="6371",ATTR{index}=="0" , MODE:="0777", SYMLINK+="cam-1"
解释一下这里的信息分别代表什么:
“1-4”就是步骤2红字部分
idVendor 和 idProduct 就是步骤1得到的设备名字
{index}也是在步骤2加粗部分获取的
SYMLINK自己随便取就好啦~
4.执行以下命令,使udev规则生效:
sudo udevadm control --reload-rules
sudo service udev restart
sudo udevadm trigger
5.检查
终端输入:
ls -l /dev |grep video
得到:
lrwxrwxrwx 1 root root 6 7月 9 16:03 cam-1 -> video0
lrwxrwxrwx 1 root root 6 7月 9 16:03 cam-2 -> video2
crw-rw---- 1 root video 29, 0 7月 9 16:03 fb0
crw-rw---- 1 root video 238, 0 7月 9 16:03 media0
crw-rw---- 1 root video 238, 1 7月 9 16:03 media1
crwxrwxrwx+ 1 root root 81, 0 7月 9 16:03 video0
crw-rw----+ 1 root video 81, 1 7月 9 16:03 video1
crwxrw-rwx+ 1 root root 81, 2 7月 9 16:03 video2
crwxrwxrwx+ 1 root video 81, 3 7月 9 16:03 video3
可以看到已经成功绑定啦
使用opencv c++打开相机:
VideoCapture capture(0);VideoCapture cam(2);
6.结论
执行以上操作后,实测怎么插拔id都不会再变化了,只要usb口不换就行!