Create openCV VideoCapture from interface name instead of camera numbers

后端 未结 5 882
眼角桃花
眼角桃花 2020-12-17 20:13

The normal way to create a videocapture is this:

cam = cv2.VideoCapture(n)

where n corresponds to the number of /dev/video0,

5条回答
  •  囚心锁ツ
    2020-12-17 20:50

    import re
    import subprocess
    import cv2
    import os
    
    device_re = re.compile("Bus\s+(?P\d+)\s+Device\s+(?P\d+).+ID\s(?P\w+:\w+)\s(?P.+)$", 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
    

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

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

提交回复
热议问题