2

PyQt5系列教程(三十)屏幕录制

 1 year ago
source link: https://xugaoxiang.com/2022/09/13/pyqt5-30-record/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

软硬件环境

  • Windows 10 64bit
  • Anaconda3 with python 3.8
  • PyQt5 5.15

本篇来实现屏幕录制,这里使用的 pillowopencvnumpy 来实现,通过抓取一帧帧的屏幕图像,然后将其转换成 numpy 的数据,接着转换成 opencv 的格式,最后进行存储,如此循环。

首先安装需要用到的几个库

pip install pillow opencv-python numpy

接下来看看代码

import sys
import numpy as np
import cv2
from PIL import ImageGrab
from threading import Thread

from PyQt5.QtWidgets import QMainWindow, QApplication

from ui import Ui_MainWindow

class MainWindow(QMainWindow, Ui_MainWindow):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)

        # 标志位
        self.record_flag = False

        # 绑定信号与槽
        self.pushButton_start.clicked.connect(self.start)
        self.pushButton_stop.clicked.connect(self.stop)

    def start(self):
        self.pushButton_start.setEnabled(False)
        self.pushButton_stop.setEnabled(True)

        # 开启线程
        self.th = Thread(target=self.start_recording)
        self.th.start()

    def start_recording(self):
        # 抓取一张图,得到宽和高
        img = ImageGrab.grab()
        width, height = img.size
        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        fps = 30
        out = cv2.VideoWriter('record.avi', fourcc, fps, (width, height))

        while True:
            img = ImageGrab.grab()
            img_cv = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2RGB)
            out.write(img_cv)

            if self.record_flag:
                out.release()
                break

    def stop(self):
        self.record_flag = True
        self.pushButton_start.setEnabled(True)
        self.pushButton_stop.setEnabled(False)

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

https://github.com/xugaoxiang/learningPyQt5

PyQt5系列教程

更多PyQt5教程,请移步

https://xugaoxiang.com/category/python/pyqt5/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK