本文介绍了从接口名称而不是摄像机编号创建openCV VideoCapture的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The normal way to create a videocapture is this:

cam = cv2.VideoCapture(n)

其中n对应于/dev/video0dev/video1

但是,因为我要构建一个使用多个摄像机来执行不同操作的机器人,所以我需要确保已将其分配给正确的摄像机,所以我创建了udev规则,该规则创建的设备在每次出现以下情况时都指向正确端口的符号链接特定的相机已插入.

But because I'm building a robot that uses multiple cameras for different things, I needed to make sure that it was being assigned to the correct camera, I created udev rules that created devices with symbolic links to the correct port whenever a specific camera was plugged in.

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

They appear to be working because when I look in the /dev directory I can see the link:

/dev/front_cam -> video1

但是我不确定现在如何实际使用它.

However I'm not sure how to actually use this now.

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

I thought I could just open it from the filename, as if it was a video, but cam = cv2.VideoCapture('/dev/front_cam') doesn't work.

cv2.VideoCapture('/dev/video1')

它不会引发错误,它会返回一个VideoCapture对象,只是没有打开一个对象(cam.isOpened()返回False).

It doesn't throw an error, it does return a VideoCapture object, just not one that's opened (cam.isOpened() returns False).

推荐答案

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设备列表中搜索所需的字符串.获取总线和设备号.

First search for desired string in USB devices list. Get BUS and DEVICE number.

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

Find symbolic link under video4linux directory. Extract device index from realpath and pass it to VideoCapture method.

这篇关于从接口名称而不是摄像机编号创建openCV VideoCapture的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-13 21:34