用python写一个能获取USB设备视频流的小工具
时间: 2024-12-13 21:15:12 浏览: 7
Python显示多路USB摄像头.zip
在Python中,我们可以利用`pyudev`库来检测USB设备,并结合一些图像处理库如`opencv-python`来获取视频流。以下是一个简单的示例,展示如何编写一个小工具来扫描USB摄像头并打开其视频流:
```python
import cv2
import pyudev
def find_usb_cameras():
context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
monitor.filter_by('video4linux2')
for device in iter(monitor.poll, None):
if device.action == 'add':
try:
vid_pid = (device.device_info['ID_VID'], device.device_info['ID_PID'])
camera_device = '/dev/video{}'.format(device.device_node.split('/')[-1])
# 尝试打开摄像头
cap = cv2.VideoCapture(camera_device)
if cap.isOpened():
print("Found USB Camera with ID: {}, Device Path: {}".format(vid_pid, camera_device))
yield cap
except Exception as e:
print("Error accessing {} - {}".format(device.device_node, str(e)))
# 使用这个函数打开第一个找到的USB摄像头
for cap in find_usb_cameras():
while True:
ret, frame = cap.read() # 获取一帧
if not ret:
break
cv2.imshow('USB Camera Stream', frame) # 显示帧
key = cv2.waitKey(1)
if key & 0xFF == ord('q'): # 按 q 键退出
break
cap.release()
cv2.destroyAllWindows()
阅读全文