PYQT5动态背景

使用cv2结合pyqt5实现动态背景效果

代码如下:

import sys
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QApplication, QMainWindow,QLabel
from PyQt5.QtCore import QTimer
import cv2
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(100, 100, 800, 600)
        self.execute_trend('Gargantua_BGM.mp4')  #你自己的MP4文件路径

    def execute_trend(self, Path):
        self.trend_theme = QLabel(self)
        self.trend_theme.resize(self.size())
        self.trend_theme.setScaledContents(True)
        self.trend_theme.lower()
        self.cap = cv2.VideoCapture(Path)
        if not self.cap.isOpened():
            print("文件打开失败")
        self.timer_trend = QTimer(self)
        self.timer_trend.timeout.connect(self.update_frame)
        self.timer_trend.start(10)  #设置帧数1000/括号里的参数=帧数

    def stop_dynamic_background(self):
        # 停止计时器
        self.timer_trend.stop()
        # 清除label内容或隐藏label
        self.trend_theme.clear()  # 清除显示的内容
        self.trend_theme.hide()  # 隐藏label
        self.update()

    def update_frame(self):
        ret, frame = self.cap.read()
        if ret:
            # 转换帧为RGBA以添加透明度通道
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA)
            # frame[:, :, 3] = np.ones((frame.shape[0], frame.shape[1])) * 200  # 调整透明度
            # 缩放帧以适应窗口
            frame_resized = self.resize_frame(frame)
            # 转换为QImage
            height, width, channel = frame_resized.shape
            bytesPerLine = 4 * width
            image = QImage(frame_resized.data, width, height, bytesPerLine,
                           QImage.Format_ARGB32)
            pix = QPixmap.fromImage(image)
            self.trend_theme.setPixmap(pix)
        else:
            # 视频循环播放
            self.cap.set(cv2.CAP_PROP_POS_FRAMES, 0)

    def resize_frame(self, frame):
        window_width = self.width()
        window_height = self.height()
        height, width, _ = frame.shape
        scaling_factor = min(window_width / width, window_height / height)
        new_size = (int(width * scaling_factor), int(height * scaling_factor))
        frame_resized = cv2.resize(frame, new_size, interpolation=cv2.INTER_AREA)
        return frame_resized

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

注释大多都包含在了代码里 有不懂的可以评论问我

更多功能请关注我的网站:fcyang.top

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值