pyqt5-结合opencv展示实时视频纯Demo


前言


一、代码

'''
#Author :susocool
#Creattime:2024/5/22
#FileName:018.1-显示摄像头
#Description: 

'''
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtWidgets import QHBoxLayout
import cv2
import os

class VideoDisplay(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("视频展示~")
        self.setGeometry(100, 100, 600, 600)

        self.label = QtWidgets.QLabel(self)
        self.label.setGeometry(QtCore.QRect(50, 50, 500, 500))

        self.video = cv2.VideoCapture(0)
        self.width = int(self.video.get(cv2.CAP_PROP_FRAME_WIDTH))
        self.height = int(self.video.get(cv2.CAP_PROP_FRAME_HEIGHT))
        self.ratio1 = self.width / 500
        self.ratio2 = self.height / 500
        self.ratio = max(self.ratio1, self.ratio2)

        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.updateFrame)
        self.timer.start(10)

        # 创建水平布局和按钮
        self.button_layout = QtWidgets.QHBoxLayout ()

        self.save_button = QtWidgets.QPushButton ( '保存图片', self )
        self.save_button.clicked.connect ( self.saveImage )
        self.button_layout.addWidget ( self.save_button )

        self.exit_button = QtWidgets.QPushButton ( '退出界面', self )
        self.exit_button.clicked.connect ( self.exitApplication )
        self.button_layout.addWidget ( self.exit_button )

        # 设置按钮布局的位置
        self.button_layout.setGeometry ( QtCore.QRect(60, 500, 500, 60 ) )

    def updateFrame(self):
        ret, frame = self.video.read()
        if not ret:
            return

        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        picture = QtGui.QImage(frame_rgb.data, self.width, self.height, 3 * self.width, QtGui.QImage.Format_RGB888)
        pixmap = QtGui.QPixmap.fromImage(picture)
        pixmap.setDevicePixelRatio(self.ratio)
        self.label.setPixmap(pixmap)
        self.label.show()

    def saveImage(self):
        ret, frame = self.video.read()
        if not ret:
            return

        file_path, _ = QtWidgets.QFileDialog.getSaveFileName(self, 'Save Image', os.path.expanduser('~'), 'Images (*.png *.jpg *.jpeg)')
        if file_path:
            cv2.imwrite(file_path, frame)

    def exitApplication(self):
        self.video.release()
        self.timer.stop()
        self.close()

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    ex = VideoDisplay()
    ex.show()
    sys.exit(app.exec_())

二、运行结果

在这里插入图片描述
--------------------------------------------2024/5/22


总结

这篇文章依旧没有总结

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值