如何使用Python OpenCV实现3台及以上移动摄像头的多线程采集与同屏分析
四路摄像头同屏采集+QR识别实现方案
实现思路
- 设备映射:Iriun Cam连接成功的4台手机会在系统中生成4个独立的视频捕获设备,默认设备ID依次为0、1、2、3,可提前逐个测试ID对应关系
- 多线程采集:为每个摄像头启动独立的读取线程,避免单线程串行读取导致的帧率下降、画面卡顿延迟
- 2x2画面拼接:将4路摄像头输出的帧统一缩放到相同尺寸后,拼接为单张大图在同一窗口展示
- 全量QR识别:每轮循环对4路帧分别做QR解码,汇总所有识别结果后和目标集合做匹配校验
修改后可运行代码
import numpy as np import cv2 import threading from pyzbar.pyzbar import decode # 摄像头读取线程类,避免单线程读多路卡顿 class CameraCapture(threading.Thread): def __init__(self, device_id, width=640, height=480): super().__init__() self.cap = cv2.VideoCapture(device_id) self.cap.set(3, width) self.cap.set(4, height) self.running = True self.frame = None def run(self): while self.running: success, frame = self.cap.read() if success: self.frame = frame def stop(self): self.running = False self.cap.release() # 初始化4路摄像头,设备ID按实际情况调整 cams = [ CameraCapture(0), CameraCapture(1), CameraCapture(2), CameraCapture(3) ] # 启动所有采集线程 for cam in cams: cam.start() # 目标校验集合 A = ['A9', 'I2', 'I19', 'I20', 'J1', 'J2', 'J20'] target_set = set(A) while True: all_qr_data = [] frames = [] # 读取所有摄像头最新帧 for cam in cams: if cam.frame is not None: # 拷贝帧避免线程读写冲突 frame = cam.frame.copy() frames.append(frame) # 识别当前帧的QR码 for barcode in decode(frame): qr_text = barcode.data.decode('utf-8') all_qr_data.append(qr_text) # 给识别到的QR码画框 pts = np.array([barcode.polygon], np.int32) pts = pts.reshape((-1,1,2)) cv2.polylines(frame, [pts], True, (255,0,255), 5) # 校验识别结果 current_set = set(all_qr_data) if current_set == target_set: print("识别结果:", all_qr_data) print("Authorised") else: print("Not authorised") # 2x2拼接四路画面 if len(frames) == 4: top = np.hstack((frames[0], frames[1])) bottom = np.hstack((frames[2], frames[3])) full_screen = np.vstack((top, bottom)) cv2.imshow('四路摄像头同屏', full_screen) # 按q退出 if cv2.waitKey(1) & 0xFF == ord('q'): break # 释放资源 for cam in cams: cam.stop() cv2.destroyAllWindows()
注意事项
- 运行前先逐个测试摄像头ID是否正确,替换代码中CameraCapture的设备ID参数即可
- 若出现画面卡顿,可降低单路摄像头的分辨率参数,或调整Iriun Cam的传输码率
- QR码识别率低时,可在识别前对帧做灰度化、高斯模糊预处理,提升识别准确率
内容的提问来源于stack exchange,提问作者Pratham Naik
相关产品推荐
相关产品推荐

