从接口名而不是摄像机号创建openCV视频捕获

2024-09-27 02:27:11 发布

您现在位置:Python中文网/ 问答频道 /正文

创建视频捕获的常规方法是:

cam = cv2.VideoCapture(n)

其中n对应于/dev/video0dev/video1的个数

但是因为我正在构建一个机器人,它使用多个摄像头来完成不同的任务,所以我需要确保它被分配给正确的摄像头,我创建了udev规则,每当插入特定的摄像头时,都会创建具有指向正确端口的符号链接的设备。

它们似乎在工作,因为当我查看/dev目录时,可以看到链接:

/dev/front_cam -> video1

但是我不知道现在该怎么用。

我以为我可以从文件名打开它,就好像它是一个视频一样,但是cam = cv2.VideoCapture('/dev/front_cam')不起作用。

也不是cv2.VideoCapture('/dev/video1')

它不会抛出错误,而是返回一个VideoCapture对象,而不是打开的对象(cam.isOpened()返回False)。


Tags: 对象方法dev视频链接机器人cv2常规
3条回答

我的每个video4linux设备创建2个设备节点。例如,/dev/video0/dev/video1都与我的内部网络摄像头相关。当我插入第二个USB摄像头时,/dev/video2/dev/video3都会出现。但是,我只能使用每对中编号较低的设备进行视频捕获(即/dev/video0/dev/video2)。

我用udevadm monitor观看设备到达,然后用udevadm info --path=$PATH_FROM_UDEVADM_MONITOR --attribute-walk检查每个相机设备。用于视频捕获的设备有ATTR{index}=="0"

也许你只需要打开/dev/video0,而不是试图打开/dev/video1

cam = cv2.CaptureVideo("/dev/video0")

我没有找到建议的解决方案,而是找到了一个短一点的,感觉有点粗糙。

我只是看看符号链接点的位置,找到其中的整数,然后使用它。

import subprocess

cmd = "readlink -f /dev/CAMC"
process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)

# output of form /dev/videoX
out = process.communicate()[0]

# parse for ints
nums = [int(x) for x in out if x.isdigit()]

cap = cv2.VideoCapture(nums[0])
import re
import subprocess
import cv2
import os

device_re = re.compile("Bus\s+(?P<bus>\d+)\s+Device\s+(?P<device>\d+).+ID\s(?P<id>\w+:\w+)\s(?P<tag>.+)$", re.I)
df = subprocess.check_output("lsusb", shell=True)
for i in df.split('\n'):
    if i:
        info = device_re.match(i)
        if info:
            dinfo = info.groupdict()
            if "Logitech, Inc. Webcam C270" in dinfo['tag']:
                print "Camera found."
                bus = dinfo['bus']
                device = dinfo['device']
                break

device_index = None
for file in os.listdir("/sys/class/video4linux"):
    real_file = os.path.realpath("/sys/class/video4linux/" + file)
    print real_file
    print "/" + str(bus[-1]) + "-" + str(device[-1]) + "/"
    if "/" + str(bus[-1]) + "-" + str(device[-1]) + "/" in real_file:
        device_index = real_file[-1]
        print "Hurray, device index is " + str(device_index)


camera = cv2.VideoCapture(int(device_index))

while True:
    (grabbed, frame) = camera.read() # Grab the first frame
    cv2.imshow("Camera", frame)
    key = cv2.waitKey(1) & 0xFF

首先在USB设备列表中搜索所需的字符串。获取总线和设备号。

在video4linux目录下找到符号链接。从realpath中提取设备索引并将其传递给VideoCapture方法。

相关问题 更多 >

    热门问题