以编程方式选择相机

Fel*_*lix 3 python camera python-3.x

我的程序应该选择三个相机并用每个相机拍照。

我现在有以下代码:

def getCamera(camera):
    graph = FilterGraph()
    print("Camera List: ")
    print(graph.get_input_devices())

    #tbd get right Camera

    try:
        device = graph.get_input_devices().index("HD Pro Webcam C920")
    except ValueError as e:
        device = graph.get_input_devices().index("Integrated Webcam")
    return device
Run Code Online (Sandbox Code Playgroud)

上面的代码运行良好。但我有三台类似的同名相机。

输出:

graph = FilterGraph()
print("Camera List: ")
print(graph.get_input_devices())
Run Code Online (Sandbox Code Playgroud)

是一个包含三个同名相机的列表。我认为它们在一个数组中,我可以这样选择它们:

device = graph.get_input_devices().index(0) 
Run Code Online (Sandbox Code Playgroud)

与任何其他数组一样。

但我只能通过名称访问。就像第一个代码示例一样。

如何通过索引访问摄像机?

小智 6

您可以使用列表中摄像机的索引来选择它。例如,如果要选择列表中的第一个摄像机,可以使用以下代码:

device = graph.get_input_devices().index("HD Pro Webcam C920")
Run Code Online (Sandbox Code Playgroud)

选择第二个摄像头:

device = graph.get_input_devices().index("HD Pro Webcam C920", 1)
Run Code Online (Sandbox Code Playgroud)

要选择第三个摄像头,您可以使用:

device = graph.get_input_devices().index("HD Pro Webcam C920", 2)
Run Code Online (Sandbox Code Playgroud)

index()方法中的第二个参数指定搜索的起始索引。

您还可以修改getCamera()函数以获取指定要使用的相机索引的参数:

def getCamera(camera_index):
    graph = FilterGraph()
    cameras = graph.get_input_devices()
    if camera_index >= len(cameras):
        raise ValueError("Camera index out of range")
    return cameras[camera_index]

for i in range(3):
    camera = getCamera(i)
    #Do something with it
Run Code Online (Sandbox Code Playgroud)