[Python] Enumerate over cameras in Python

Discussão em 'Python' iniciado por Stack, Fevereiro 4, 2025.

  1. Stack

    Stack Membro Participativo

    I'm having some trouble enumerating over cameras in Python over multiple OS's.

    Here's some of the approaches I've tried:

    import cv2 as cv
    num = 0
    while 1:
    cap = cv.VideoCapture(num)
    if cap.isOpened():
    # working capture
    num += 1
    else:
    break


    The downsides of using Opencv is that Opencv doesn't provide any friendly display name. Additionally, enumerating over cameras is slow, as you need to actually open and close the camera to check if it's a valid camera.

    I've also tried using libraries like PyPylon and pyuvc. They work, but only for specific brands.

    I've done some researching on stack overflow, and some people have suggested python's gstreamer bindings as a possible OS independent solution. This is what I have so far.

    import pgi
    pgi.require_version("Gtk", "3.0")
    pgi.require_version("Gst", "1.0")
    pgi.require_version("GstVideo", "1.0")
    from pgi.repository import Gtk, GObject, Gst, GstVideo

    Gst.init("")
    dm = Gst.DeviceMonitor()
    dm.set_show_all_devices(True)

    dm.start()

    print("Displaying devices.")
    for device in dm.get_devices():
    print(device.get_display_name())
    print("Displaying providers.")
    for provider in dm.get_providers():
    print(provider)

    dm.stop()


    This is the output I'm getting:

    Displaying devices.
    papalook Microphone
    DisplayPort
    HDMI
    Built-in Output
    Built-in Microph
    Displaying providers.
    osxaudiodeviceprovider


    For some reason, I'm not getting any webcams, but only audio devices. Any ideas on what I'm doing wrong? Any different approaches I should be taking? Thanks.

    Continue reading...

Compartilhe esta Página