簡體   English   中英

列出可用的相機 OpenCV/Python

[英]List available cameras OpenCV/Python

我有多個網絡攝像頭連接到我的 PC,我想根據其信息(名稱、分辨率等)選擇一個攝像頭。 有沒有辦法列出 PC 上所有可用的攝像機,而不是嘗試 cv2.VideoCapture() 中的所有索引?

要回答問題的標題,您可以使用 while 循環:

import cv2


def list_ports():
"""
Test the ports and returns a tuple with the available ports and the ones that are working.
"""
    is_working = True
    dev_port = 0
    working_ports = []
    available_ports = []
    while is_working:
        camera = cv2.VideoCapture(dev_port)
        if not camera.isOpened():
            is_working = False
            print("Port %s is not working." %dev_port)
        else:
            is_reading, img = camera.read()
            w = camera.get(3)
            h = camera.get(4)
            if is_reading:
                print("Port %s is working and reads images (%s x %s)" %(dev_port,h,w))
                working_ports.append(dev_port)
            else:
                print("Port %s for camera ( %s x %s) is present but does not reads." %(dev_port,h,w))
                available_ports.append(dev_port)
        dev_port +=1
    return available_ports,working_ports

這是在您的代碼上實現的一個非常簡單的解決方案。

答案是否定的。 OpenCV 沒有列出系統上可用視頻捕獲設備的方法。 如果您查看代碼,您會看到 OpenCV 當前如何處理不存在的無效設備索引。 例如對於 MacOS,這里是代碼

if ( cameraNum < 0 || devices.count <= NSUInteger(cameraNum) ) {
    fprintf(stderr, "OpenCV: out device of bound (0-%ld): %d\n", devices.count-1, cameraNum);
    [localpool drain];
    return 0;
}

您會看到devices.count返回可用設備的數量,但 OpenCV 沒有將其返回給用戶的方法。

Windows 的相關代碼在這里

if ((unsigned)m_deviceID >= m_devices.Get()->Size)
{
    OutputDebugStringA("Video::initGrabber - no video device found\n");
    return false;
}

同樣沒有將m_devices.Get()->Size返回給用戶的函數。 Linux 代碼有點復雜。

如果您從代碼構建 OpenCV,您可以添加一個返回可用設備數量的函數。 或者甚至更好地向 OpenCV 提交拉取請求以及您的補丁。

第一個安裝包:pip install pygrabber==0.1

代碼 #

from pygrabber.dshow_graph import FilterGraph

graph = FilterGraph()

print(graph.get_input_devices())# list of camera device 

try:
    device =graph.get_input_devices().index("name camera that I want to use it ")

except ValueError as e:

    device = graph.get_input_devices().index("Integrated Webcam")#use default camera if the name of the camera that I want to use is not in my list

vid=cv2.VideoCapture(device)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM