Python 屏幕录制教程:使用 pyautogui 和 opencv-python
Python 屏幕录制教程:使用 pyautogui 和 opencv-python
想要在 Python 中录制屏幕内容?你可以使用第三方库 pyautogui 和 opencv-python。下面是一个简单的示例代码:
import cv2
import pyautogui
import numpy as np
# 获取屏幕的宽度和高度
screen_info = pyautogui.screen_info()
screen_width, screen_height = screen_info['width'], screen_info['height']
# 设置输出视频的编解码器和分辨率
fourcc = cv2.VideoWriter_fourcc(*'XVID')
output = cv2.VideoWriter('output.avi', fourcc, 20.0, (screen_width, screen_height))
while True:
    # 获取屏幕截图
    img = pyautogui.screenshot()
    frame = np.array(img)
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    
    # 写入视频文件
    output.write(frame)
    
    # 显示录制的屏幕
    cv2.imshow('Screen Recording', frame)
    
    # 按下'q'键停止录制
    if cv2.waitKey(1) == ord('q'):
        break
# 释放资源
output.release()
cv2.destroyAllWindows()
这段代码将会录制屏幕并保存为名为 output.avi 的视频文件。你可以使用 cv2.VideoCapture 来读取和播放这个视频文件。
请确保你已经安装了 pyautogui 和 opencv-python 库。
安装方法:
pip install pyautogui opencv-python
原文地址: https://www.cveoy.top/t/topic/SpK 著作权归作者所有。请勿转载和采集!