2016-03-06 33 views
4

正常的方式来创建一个videocapture是这样的:从接口名称,而不是摄像机号创建OpenCV的VideoCapture

cam = cv2.VideoCapture(n)

,其中n对应于/dev/video0数量,dev/video1

但因为我m建立了一个机器人,它使用多个摄像头来处理不同的事情,我需要确保它被分配给正确的摄像头,我创建了udev规则,创建带有符号链接到正确端口的设备,每当插入特定摄像头时。

他们似乎是工作,因为当我看着在/dev目录,我可以看到链接:

/dev/front_cam -> video1

但是我不知道如何实际现在用的这个。

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

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

它不会抛出一个错误,它返回一个VideoCapture对象,只是没有一个年开幕(cam.isOpened()返回False)。

+0

可以从您的程序读取符号链接,这样就可以得到字符串“的/ dev /视频1”编程?如果是的话,你可以从该字符串中提取数字(1)并将其提供给openCV捕获对象? – Micka

+1

我upvoted你的问题,我认为很好的问题。 – mertyildiran

回答

1
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设备列表中搜索所需的字符串。获取BUS和DEVICE号码。

查找video4linux目录下的符号链接。从实际路径中提取设备索引并将其传递给VideoCapture方法。

1

而不是建议的解决方案,我发现一个较短的,这感觉有点哈克。

我只是看看符号链接指向哪里,找到它的整数,然后使用它。

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])