You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用cv2开发带鼠标光标的录屏工具输出视频无法播放

屏幕录制工具视频无法播放问题修复

问题根因

  • 你使用的XVID编码仅支持3通道BGR格式的帧输入,代码中传入的是4通道RGBA图像,编码不兼容直接导致生成的视频文件损坏无法播放
  • PIL生成的图像为RGB通道顺序,而OpenCV的VideoWriter默认要求输入BGR顺序的图像,通道顺序错位也会引发编码异常
  • 循环内重复读取光标图片资源,多余的IO操作也可能引发偶发的文件读取错误导致录制中断

修复后代码

import cv2
import os
import pyautogui
from PIL import Image
import numpy as np
import keyboard

screen_size = pyautogui.size()
# 显式转换为整数元组,避免部分环境下参数类型不兼容问题
frame_size = (int(screen_size.width), int(screen_size.height))
FPS = 11.0

def recorder(frame_size, FPS):
    fourcc = cv2.VideoWriter_fourcc(*"XVID")
    video = cv2.VideoWriter("VIDEO.avi", fourcc, FPS, frame_size)
    # 提前预加载光标资源,避免循环内重复IO
    ruta_actual = os.getcwd()
    cursor_img = Image.open(os.path.join(ruta_actual, "resources", "cursor_state0.png")).convert("RGBA")
    start = input("输入y开始录制:")
    if start == "y":
        print(f"录制中,按p键停止录制")
        while True:
            if keyboard.is_pressed("p"):
                break
            # 截取屏幕、获取光标位置
            screenshot_img = pyautogui.screenshot()
            x, y = pyautogui.position()
            # 叠加光标
            complete_img = Image.new('RGBA', frame_size, (0, 0, 0, 0))
            complete_img.paste(screenshot_img, (0, 0))
            complete_img.paste(cursor_img, (x, y), cursor_img)
            # 格式转换:RGBA转BGR,适配OpenCV编码要求
            data = np.array(complete_img)
            data = cv2.cvtColor(data, cv2.COLOR_RGBA2BGR)
            video.write(data)
        # 释放资源
        video.release()
        cv2.destroyAllWindows()
        print("录制已结束,文件已保存为VIDEO.avi")

if __name__ == "__main__":
    recorder(frame_size, FPS)

额外优化建议

  • 如果录制后发现光标位置偏移,可以减去光标图片自身的宽高偏移量,调整粘贴位置为(x - cursor_width//2, y - cursor_height//2)
  • FPS可以根据你的设备性能调整到15~24,观看流畅度会更高
  • 建议增加异常捕获逻辑,避免录制过程中意外退出导致视频文件损坏

内容的提问来源于stack exchange,提问作者JGallego

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 01:27:07