python同时读取四个摄像头
时间: 2023-07-17 18:06:53 浏览: 118
要同时读取四个摄像头,你可以使用OpenCV库。下面是一个示例代码,展示了如何使用多线程同时读取四个摄像头的视频流:
```python
import cv2
import threading
# 摄像头索引
camera_indices = [0, 1, 2, 3]
# 读取视频流的线程类
class CameraThread(threading.Thread):
def __init__(self, camera_index):
threading.Thread.__init__(self)
self.camera_index = camera_index
self.video_capture = cv2.VideoCapture(camera_index)
self.frame = None
self.running = True
def run(self):
while self.running:
ret, frame = self.video_capture.read()
if ret:
self.frame = frame
def stop(self):
self.running = False
self.join()
# 创建多个摄像头线程并启动
camera_threads = []
for index in camera_indices:
thread = CameraThread(index)
thread.start()
camera_threads.append(thread)
# 主循环
while True:
# 显示每个摄像头的视频流
for index, thread in enumerate(camera_threads):
frame = thread.frame
if frame is not None:
cv2.imshow(f"Camera {index}", frame)
# 按下 'q' 键退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 停止并释放摄像头线程和资源
for thread in camera_threads:
thread.stop()
thread.video_capture.release()
cv2.destroyAllWindows()
```
在上面的示例中,我们定义了一个`CameraThread`类,用于读取每个摄像头的视频流。每个线程都会在后台不断读取视频帧,并将最新的帧存储在`frame`属性中。主循环中,我们通过遍历每个摄像头线程,显示其对应的视频帧。
你可以通过修改`camera_indices`列表来指定要读取的摄像头索引。根据你的需求,你可以进一步处理每个摄像头的视频帧,例如进行图像处理、目标检测等。同时,请确保你已经正确安装了OpenCV库。
阅读全文