赞
踩
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
import cv2
class Ui_MainWindow(QtWidgets.QWidget):
def __init__(self, parent=None): super().__init__(parent) self.timer_cameras = [] # 为每个摄像头定义一个定时器 self.caps = [] # 存储每个摄像头的VideoCapture self.CAM_NUMS = [0, 1, 2, 3] # 包括电脑上的摄像头和三个外接摄像头的编号 self.set_ui() self.slot_init() def set_ui(self): self.__layout_main = QtWidgets.QHBoxLayout() # 创建四个 QLabel 用于显示四个摄像头画面 self.label_cameras = [QtWidgets.QLabel() for _ in range(4)] for label_camera in self.label_cameras: label_camera.setFixedSize(320, 240) label_camera.setStyleSheet('''QWidget{border-radius:7px;background-color:#d3d3d3;}''') self.__layout_fun_button = QtWidgets.QVBoxLayout() self.button_open_cameras = QtWidgets.QPushButton('打开摄像头') self.button_close = QtWidgets.QPushButton('退出') self.button_open_cameras.setMinimumHeight(50) self.button_close.setMinimumHeight(50) self.__layout_fun_button.addWidget(self.button_open_cameras) self.__layout_fun_button.addWidget(self.button_close) self.__layout_main.addLayout(self.__layout_fun_button) # 将四个 QLabel 加入到总布局中 for label_camera in self.label_cameras: self.__layout_main.addWidget(label_camera) self.setLayout(self.__layout_main) def slot_init(self): self.button_open_cameras.clicked.connect(self.button_open_cameras_clicked) self.button_close.clicked.connect(self.close) # 初始化定时器和摄像头 for i, cam_num in enumerate(self.CAM_NUMS): timer_camera = QtCore.QTimer() self.timer_cameras.append(timer_camera) cap = cv2.VideoCapture() self.caps.append(cap) self.timer_cameras[i].timeout.connect(lambda i=i, cam_num=cam_num: self.show_camera(i, cam_num)) def button_open_cameras_clicked(self): for i, cam_num in enumerate(self.CAM_NUMS): if not self.timer_cameras[i].isActive(): flag = self.caps[i].open(cam_num, cv2.CAP_DSHOW) if not flag: msg = QtWidgets.QMessageBox.warning(self, 'warning', f"请检查相机 {cam_num} 是否连接正确", buttons=QtWidgets.QMessageBox.Ok) else: self.timer_cameras[i].start(30) self.button_open_cameras.setText('关闭摄像头') if any(timer.isActive() for timer in self.timer_cameras) else self.button_open_cameras.setText('打开摄像头') def show_camera(self, index, cam_num): flag, image = self.caps[index].read() image = cv2.flip(image, 1) show = cv2.resize(image, (320, 240)) show = cv2.cvtColor(show, cv2.COLOR_BGR2RGB) show_image = QtGui.QImage(show.data, show.shape[1], show.shape[0], QtGui.QImage.Format_RGB888) self.label_cameras[index].setPixmap(QtGui.QPixmap.fromImage(show_image))
if name == ‘main’:
app = QtWidgets.QApplication(sys.argv)
ui = Ui_MainWindow()
ui.show()
sys.exit(app.exec_())
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。