Search code examples
pythonpython-3.xcamera

Select camera programatically


My program should select three cameras and take pictures with each of it.

I have the following code at the moment:

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

The code above worked fine. But I have three similar cameras with the same name.

Output of this:

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

Is a list with three cameras all the same name. I thought they are in an array and I can select them with this:

device = graph.get_input_devices().index(0) 

Like any other Array.

But I only can access with the Name. Like in the first code example.

How can I access the cameras with index?


Solution

  • You can use the index of the camera in the list to select it. For example, if you want to select the first camera in the list, you can use the following code:

    device = graph.get_input_devices().index("HD Pro Webcam C920")
    

    To select the second camera:

    device = graph.get_input_devices().index("HD Pro Webcam C920", 1)
    

    And to select the third camera, you can use:

    device = graph.get_input_devices().index("HD Pro Webcam C920", 2)
    

    The second argument in the index() method specifies the starting index for the search.

    You can also modify your getCamera() function to take an argument that specifies the index of the camera you want to use:

    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