Pytside2+Opencv在上位机实时显示视频流数据,并且可以选择相应的摄像头(主机自带摄像头或者外接摄像头)可以控制开关
根据选中的单选按钮获取相应的视频源,并实时显示视频流了。当点击不同的单选按钮时,程序会自动释放当前摄像头,然后打开新的摄像头以获取选中的视频源。
ui界面
from PySide2.QtWidgets import QApplication
from PySide2.QtUiTools import QUiLoader
import cv2
from PySide2.QtWidgets import *
from PySide2.QtGui import QImage, QPixmap
from PySide2.QtCore import Qt, QTimer
class Mainwindow(object):
def __init__(self):
# 加载ui文件
self.ui = QUiLoader().load('ui/untitled.ui')
# 连接按钮的点击事件
self.ui.button1.clicked.connect(self.open)
self.ui.button.clicked.connect(self.close)
self.ui.button2.clicked.connect(self.print_plain_text)
# 连接单选按钮的点击事件
self.ui.radioButton1.clicked.connect(lambda: self.on_radio_button_clicked(self.ui.radioButton1))
self.ui.radioButton2.clicked.connect(lambda: self.on_radio_button_clicked(self.ui.radioButton2))
# 设置初始视频源
self.video_source = "选项1" # 更新为默认视频源
# 创建视频捕获对象并打开初始视频源
self.camera = cv2.VideoCapture(self.video_source, cv2.CAP_DSHOW)
# 初始化摄像头状态和定时器
self.is_camera_running = True
self.timer = QTimer()
# 连接定时器的超时事件到update_frame方法
self.timer.timeout.connect(self.update_frame)
# 设置定时器间隔为30毫秒,确保定期更新摄像头画面
self.timer.start(30)
def update_frame(self):
# 当摄像头运行时,从摄像头读取帧并在界面上显示
if self.is_camera_running:
ret, frame = self.camera.read()
if ret:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
h, w, ch = frame.shape
bytes_per_line = ch * w
q_image = QImage(frame.data, w, h, bytes_per_line, QImage.Format_RGB888)
pixmap = QPixmap.fromImage(q_image)
self.ui.label.setPixmap(pixmap.scaled(self.ui.label.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
def print_plain_text(self):
# 获取并打印plainTextEdit的文本内容
content = self.ui.plainTextEdit.toPlainText()
print(content)
def on_radio_button_clicked(self, button):
# 单选按钮被点击时,获取选中的文本并更新视频源
if button.isChecked():
self.video_source = button.text()
print("选中的选项:", self.video_source)
# 释放当前摄像头并打开新的摄像头
self.camera.release()
self.camera = cv2.VideoCapture(self.video_source, cv2.CAP_DSHOW)
def open(self):
# 打开摄像头
print("open")
if not self.is_camera_running:
self.camera = cv2.VideoCapture(0)
self.is_camera_running = True
def close(self):
# 关闭摄像头
print("close")
if self.is_camera_running:
self.camera.release()
self.is_camera_running = False
if __name__ == '__main__':
app = QApplication([])
gui = Mainwindow()
gui.ui.show()
app.exec_()