从接口名称而不是摄像机编号创建openCV VideoCapture

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

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)对象。

回答:

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方法。

以上是 从接口名称而不是摄像机编号创建openCV VideoCapture 的全部内容, 来源链接: utcz.com/qa/401036.html

回到顶部