import cv2 import numpy as np import pyautogui
def record_screen(output_file, fps=30): # 获取屏幕宽度和高度 screen_width, screen_height = pyautogui.size() # 创建视频编码器 fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter(output_file, fourcc, fps, (screen_width, screen_height)) while True: # 捕获屏幕图像 img = pyautogui.screenshot() # 转换图像颜色空间 frame = np.array(img) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # 将图像写入视频文件 out.write(frame) # 按下q键停止录屏 if cv2.waitKey(1) == ord('q'): break # 释放资源 out.release() cv2.destroyAllWindows() print(f'录制已保存为{output_file}')
def main(): output_file = 'screencast.mp4' fps = 30 print('按下q键停止录屏') record_screen(output_file, fps)
if __name__ == '__main__': main()
这段代码使用pyautogui 库的screenshot() 方法来捕获屏幕图像,并使用opencv-python 库的VideoWriter 类来创建一个视频编码器,将捕获到的图像写入视频文件。 运行代码后,按下'q'键即可停止录屏,并将录制的视频保存为screencast.mp4 文件。 请注意,这只是一个简单的示例,可能在某些系统上无法正常工作或存在一些限制。如果需要更高级的功能,可以考虑使用第三方库,如pyav 、imageio 等。 为了实现该功能,你需要安装opencv-python 和pyautogui 库。可以使用以下命令在终端中安装这些库: pip install opencv-python pyautogui
|