import cv2
import time
# 设置目标帧尺寸
target_frame_shape = (160,120)
# 设定摄像头设备
pipeline_mipi = (
'v4l2src device=/dev/video0 ! '
'video/x-raw, format=NV12, width=640, height=480, framerate=30/1 ! '
'videoconvert ! '
'appsink'
)
# 创建摄像头捕获器
cap_mipi = cv2.VideoCapture(pipeline_mipi, cv2.CAP_GSTREAMER)
cap_usb9 = cv2.VideoCapture('/dev/video9')
cap_usb11 = cv2.VideoCapture('/dev/video11')
cap_usb13 = cv2.VideoCapture('/dev/video13')
# 检查所有摄像头是否成功打开
cams = [cap_usb9, cap_usb11]
all_opened = all(cap.isOpened() for cap in cams)
if not all_opened:
for i, cap in enumerate(cams):
if not cap.isOpened():
print(f"无法打开摄像头: /dev/video{i}")
exit()
start_time = time.time()
while True:
frames = []
for cap in cams:
ret, frame = cap.read()
if not ret:
print(f"读取摄像头帧失败")
break
# 调整帧尺寸到目标尺寸
resized_frame = cv2.resize(frame, target_frame_shape, interpolation=cv2.INTER_AREA)
frames.append(resized_frame)
# 如果所有摄像头都成功读取了帧,则进行拼接
if len(frames) == 2:
# 将前两帧水平拼接
concatenated_frames = cv2.hconcat([frames[0], frames[1]])
# 将后两帧水平拼接
concatenated_frames2 = cv2.hconcat([frames[2], frames[3]])
# 再将这两部分垂直拼接
result = cv2.vconcat([concatenated_frames, concatenated_frames2])
result = cv2.resize(result,target_frame_shape,interpolation=cv2.INTER_AREA)
cv2.imshow('All_Cameras', result )
else:
print("未能获取所有摄像头的帧")
cv2.waitKey(1)
# 若运行超过指定时间(例如60秒),则退出循环
if time.time() - start_time > 60:
break
# 释放所有摄像头资源
for cap in cams:
cap.release()
cv2.destroyAllWindows()
代码中间修改过,直接粘贴过来了,实际使用中需要适当修改。
我用的设备:RK3568,3个usb摄像头,1个mipi摄像头