当前位置: 首页 > article >正文

【PySide6拓展】QWindowCapture

文章目录

  • 【PySide6拓展】QWindowCapture 窗口捕获
    • **基本概念**
      • **什么是 QWindowCapture?**
      • **应用场景**
      • **安装 PySide6**
    • **如何使用 QWindowCapture?**
      • **1. 捕获窗口内容**
        • **示例代码:捕获当前窗口内容**
    • **代码解析**
    • **QWindowCapture 的应用场景**
      • **1. 自动化界面测试**
      • **2. 录制窗口视频**
      • **3. 远程桌面监控**
    • **总结**


【PySide6拓展】QWindowCapture 窗口捕获

QWindowCapture 是 PySide6 提供的一个窗口捕获类,它允许从指定的窗口捕获图像或视频流。该功能对于屏幕录制、窗口截图、视频流处理等应用非常有用。

本文将介绍 QWindowCapture 的基本概念、使用方法,并提供示例代码,帮助你快速掌握窗口捕获的开发。


基本概念

什么是 QWindowCapture?

QWindowCapture 允许捕获系统上的任意窗口内容,并提供 newVideoFrame 信号,用于获取实时窗口截图或视频帧数据。

应用场景

  • 窗口截图(截取指定窗口的内容)
  • 录制指定窗口(将窗口内容作为视频流输出)
  • 实时图像分析(例如 OCR 文字识别、界面自动化等)
  • 远程监控(获取应用窗口的动态画面)

安装 PySide6

如果你尚未安装 PySide6,可以使用以下命令安装:

pip install PySide6

如何使用 QWindowCapture?

1. 捕获窗口内容

QWindowCapture 主要与 QMediaCaptureSession 配合使用。以下示例展示如何使用 QWindowCapture 获取窗口图像。

示例代码:捕获当前窗口内容
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget, QPushButton
from PySide6.QtGui import QPixmap, QImage
from PySide6.QtMultimedia import QMediaCaptureSession, QWindowCapture
from PySide6.QtCore import Qt

class WindowCaptureApp(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("QWindowCapture 窗口捕获示例")
        self.resize(800, 600)

        # 创建主窗口
        central_widget = QWidget()
        layout = QVBoxLayout(central_widget)
        self.setCentralWidget(central_widget)

        # 显示捕获的图像
        self.image_label = QLabel("窗口截图将在这里显示")
        self.image_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.image_label)

        # 捕获按钮
        self.capture_button = QPushButton("截取当前窗口")
        layout.addWidget(self.capture_button)

        # 创建窗口捕获器
        self.window_capture = QWindowCapture()
        self.session = QMediaCaptureSession()
        self.session.setWindowCapture(self.window_capture)

        # 连接信号
        self.capture_button.clicked.connect(self.capture_window)
        self.window_capture.newVideoFrame.connect(self.process_frame)

    def capture_window(self):
        """ 开始捕获窗口 """
        self.window_capture.setActive(True)

    def process_frame(self, frame):
        """ 处理获取的视频帧 """
        if frame.isValid():
            image = frame.toImage()
            pixmap = QPixmap.fromImage(image)
            self.image_label.setPixmap(pixmap.scaled(400, 300, Qt.KeepAspectRatio))
            self.window_capture.setActive(False)  # 仅截取一次

if __name__ == "__main__":
    app = QApplication([])
    window = WindowCaptureApp()
    window.show()
    app.exec()

代码解析

  1. 创建 QWindowCapture 实例并关联 QMediaCaptureSession

    self.window_capture = QWindowCapture()
    self.session = QMediaCaptureSession()
    self.session.setWindowCapture(self.window_capture)
    
  2. 激活窗口捕获

    self.window_capture.setActive(True)
    
  3. 监听 newVideoFrame 信号,当窗口内容更新时获取视频帧:

    self.window_capture.newVideoFrame.connect(self.process_frame)
    
  4. QVideoFrame 转换为 QImage 并显示

    def process_frame(self, frame):
        if frame.isValid():
            image = frame.toImage()
            pixmap = QPixmap.fromImage(image)
            self.image_label.setPixmap(pixmap.scaled(400, 300, Qt.KeepAspectRatio))
    

QWindowCapture 的应用场景

1. 自动化界面测试

可以定期捕获应用界面并使用 OpenCV 进行 UI 自动化测试:

import cv2
import numpy as np

def process_frame(self, frame):
    if frame.isValid():
        image = frame.toImage()
        image = image.convertToFormat(QImage.Format_RGB888)

        width, height = image.width(), image.height()
        ptr = image.bits()
        ptr.setsize(height * width * 3)
        frame_data = np.array(ptr, dtype=np.uint8).reshape((height, width, 3))

        # OpenCV 处理(灰度化)
        gray = cv2.cvtColor(frame_data, cv2.COLOR_RGB2GRAY)
        cv2.imshow("Captured Window", gray)

2. 录制窗口视频

可以使用 QMediaRecorder 录制 QWindowCapture 捕获的视频:

from PySide6.QtMultimedia import QMediaRecorder

self.recorder = QMediaRecorder()
self.session.setRecorder(self.recorder)
self.recorder.setOutputLocation(QUrl.fromLocalFile("output.mp4"))
self.recorder.record()

3. 远程桌面监控

可以将捕获的视频帧发送到远程服务器,实现远程桌面功能:

import socket

def send_frame(self, frame):
    if frame.isValid():
        image = frame.toImage().convertToFormat(QImage.Format_RGB888)
        width, height = image.width(), image.height()
        ptr = image.bits()
        ptr.setsize(height * width * 3)
        frame_data = bytes(ptr)

        # 通过网络发送数据
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect(("192.168.1.100", 8888))
        s.sendall(frame_data)
        s.close()

总结

QWindowCapture 是 PySide6 中用于捕获窗口图像或视频流的重要类,适用于:

  • 窗口截图
  • 视频录制
  • 远程桌面
  • 界面自动化测试

通过 QWindowCapture,我们可以轻松捕获应用窗口内容,并结合 QMediaCaptureSession 进行处理或存储。希望这篇文章能帮助你快速掌握 QWindowCapture,赶快试试吧! 🎥


http://www.kler.cn/a/525709.html

相关文章:

  • AI在自动化测试中的伦理挑战
  • 【Unity3D】实现横版2D游戏——单向平台(简易版)
  • 31【api接口】
  • 构建具身智能体的时空宇宙!GRUtopia:畅想城市规模下通用机器人的生活图景
  • Effective Objective-C 2.0 读书笔记——关联对象
  • Node.js MySQL:深度解析与最佳实践
  • 程序代码篇---Python随机数
  • 【Java】微服务找不到问题记录can not find user-service
  • 每日一题——序列化二叉树
  • Python3 【集合】水平考试:精选试题和答案
  • 【redis进阶】redis 总结
  • 青少年编程与数学 02-008 Pyhon语言编程基础 07课题、数字
  • deepseek R1 14b硬件要求
  • Hive:struct数据类型,内置函数(日期,字符串,类型转换,数学)
  • SpringBoot 基础特性
  • 精灵图的知识
  • YOLOv8源码修改(4)- 实现YOLOv8模型剪枝(任意YOLO模型的简单剪枝)
  • Pytorch框架从入门到精通
  • 基于springboot+vue的扶贫助农系统的设计与实现
  • SSM开发(六) SSM整合下的CURD增删改查操作(IDEA版)