我有一个 python 环境(在 Windows 10 上),它使用 OpenCV
VideoCapture
类连接到多个 USB 摄像头。
据我所知,除了
device
类构造函数/VideoCapture
方法中的open
参数之外,没有其他方法可以识别OpenCV中的特定相机。
问题是设备参数会根据实际连接的摄像头数量和 USB 端口而变化。
我希望能够识别特定相机并找到其“设备索引”或“相机索引”,无论连接了多少个相机以及连接到哪个 USB 端口。
有人可以建议一种实现该功能的方法吗? python 代码更好,但 C++ 也可以。
据我所知,openCV 枚举设备并将其索引用作相机索引。 但它的枚举方式在后端之间可能有所不同。 不管怎样,如果你可以像 OpenCV 那样枚举设备,你就可以根据你的代码匹配设备的索引及其信息。
所以,在Windows环境下,您可以使用MSMF或DSHOW作为后端。如果您使用 MSMF 作为后端,我创建了一个简单的函数来列出设备并将其名称与其索引进行匹配。 这里:https://github.com/pvys/CV-camera-finder。
如果您使用 DSHOW 作为背景,这里有一篇不错的文章:https://www.codeproject.com/Articles/1274094/Capturing-Images-from-Camera-using-Python-and-Dire
前言,我不用windows,这个也没有经过测试,只是结合网上找到的答案和来源,做了一些修改。
遍历 USB 注册表项并解析 sub_key 字符串:
import _winreg
usb_devices=[]
index = 0
with _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SYSTEM\CurrentControlSet\Enum\USB') as root_usb:
while True:
try:
subkey = _winreg.EnumKey(root_usb, index)
usb_devices.append(subkey)
index += 1
except WindowError as e:
if e[0] == 259: # No more data is available
break
elif e[0] == 234: # more data is available
index += 1
continue
raise e
print('parse these', usb_devices)
或者可能是
Popen
一个 wmic
子进程并解析 stdout
:
from subprocess import Popen, PIPE
results1 = Popen(['wmic', 'path', 'win32_pnpentity', 'get', 'caption' '/format:list'], stdout=PIPE)
results2 = Popen(['wmic','path','Win32_SerialPort','get','DeviceID^,Caption^,Description^,Name^,ProviderType','/format:list'], stdout=PIPE)
print('parse these', results1.stdout.read())
print('parse these', results2.stdout.read())
相关,linux、mac 和 windows c++:
pip install cv2_enumerate_cameras
枚举相机信息。
import cv2
from cv2_enumerate_cameras import enumerate_cameras
# MSMF backend
for camera_info in enumerate_cameras(cv2.CAP_MSMF):
print(camera_info)
print(camera_info.path)
# DSHOW backend
for camera_info in enumerate_cameras(cv2.CAP_DSHOW):
print(camera_info)
print(camera_info.path)
创建视频捕捉
# MSMF backend
cv2.VideoCapture(camera_info.index, cv2.CAP_MSMF)
# DSHOW backend
cv2.VideoCapture(camera_info.index, cv2.CAP_DSHOW)
如果您可以通过序列号或设备和供应商 ID 来区分摄像机,则可以在使用 opencv 打开之前循环遍历所有视频设备并搜索要打开的摄像机设备。