用pyqt做两个label,使用多线程打开两个视频流,在其中展示
import sys
import cv2
from PyQt6.QtCore import QThread, pyqtSignal, Qt
from PyQt6.QtGui import QImage, QPixmap
from PyQt6.QtWidgets import QApplication, QLabel, QMainWindow, QPushButton, QVBoxLayout, QWidget
class VideoThread(QThread):
change_pixmap_signal = pyqtSignal(QImage)
def __init__(self, rtsp_url):
super().__init__()
self.rtsp_url = rtsp_url
self.running = False
def run(self):
self.running = True
cap = cv2.VideoCapture(self.rtsp_url)
# 当running标志为True时,持续捕获视频帧
while self.running:
# 读取一帧视频
ret, cv_img = cap.read()
# 如果成功读取到帧
if ret:
# 将帧从BGR格式转换为RGB格式,因为OpenCV使用BGR,而Qt使用RGB
rgb_image = cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB)
# 获取图像的高度、宽度和通道数
h, w, ch = rgb_image.shape
# 计算每行像素的字节数
bytes_per_line = ch * w
# 将OpenCV的图像格式转换为Qt的QImage格式
convert_to_Qt_format = QImage(rgb_image.data, w, h, bytes_per_line, QImage.Format.Format_RGB888)
# 将图像缩放到640x480的大小,并保持宽高比
p = convert_to_Qt_format.scaled(640, 480, aspectRatioMode=Qt.AspectRatioMode.KeepAspectRatio)
# 发送QImage对象到主线程
self.change_pixmap_signal.emit(p)
cap.release()
def stop(self):
self.running = False
self.wait()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# 设置窗口标题
self.setWindowTitle("RTSP Streams")
# 设置窗口的初始位置和大小
self.setGeometry(100, 100, 800, 600)
layout = QVBoxLayout()
self.label1 = QLabel("Stream 1")
self.label2 = QLabel("Stream 2")
self.button = QPushButton("Start Streams")
layout.addWidget(self.label1)
layout.addWidget(self.label2)
layout.addWidget(self.button)
container = QWidget()
container.setLayout(layout)
self.setCentralWidget(container)
self.thread1 = VideoThread('')# 你自己的RTSP
self.thread2 = VideoThread('')# 你自己的RTSP
# 连接VideoThread的change_pixmap_signal信号到MainWindow的update_image1和update_image2槽函数
self.thread1.change_pixmap_signal.connect(self.update_image1)
self.thread2.change_pixmap_signal.connect(self.update_image2)
# 连接按钮的clicked信号到MainWindow的start_streams槽函数
self.button.clicked.connect(self.start_streams)
def start_streams(self):
self.thread1.start()
self.thread2.start()
def update_image1(self, image):
size = self.label1.size()
scaled_image = image.scaled(size.width(), size.height(), Qt.AspectRatioMode.KeepAspectRatio)
self.label1.setPixmap(QPixmap.fromImage(scaled_image))
def update_image2(self, image):
size = self.label2.size()
scaled_image = image.scaled(size.width(), size.height(), Qt.AspectRatioMode.KeepAspectRatio)
self.label2.setPixmap(QPixmap.fromImage(scaled_image))
def closeEvent(self, event):
self.thread1.stop()
self.thread2.stop()
# 调用父类的closeEvent方法以完成窗口的关闭过程
super().closeEvent(event)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())