PyQt5 series of tutorials (thirty) screen recording

Software and hardware environment

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

foreword

This article is to achieve screen recording. Here we use pillow , opencv and numpy to achieve it. By grabbing a frame of screen image, then converting it into numpy data, then converting it into opencv format, and finally storing it, and so on. .

Practical

First install the required libraries

 pip install pillow opencv-python numpy

Next look at the code

 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_())

Source code download

https://github.com/xugaoxiang/learningPyQt5

PyQt5 series of tutorials

For more PyQt5 tutorials, please move

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

This article is reproduced from https://xugaoxiang.com/2022/09/13/pyqt5-30-record/
This site is for inclusion only, and the copyright belongs to the original author.