软硬件环境
- Windows 10 64bit
- Anaconda3 with python 3.8
- PyQt5 5.15
前言
本篇来实现屏幕录制,这里使用的 pillow、opencv
和 numpy
来实现,通过抓取一帧帧的屏幕图像,然后将其转换成 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
教程,请移步