使用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