Python cv2:视频不播放

Python cv2: Video does not play

我想制作一个屏幕录像机,并且光标出现在视频的每一帧中,为此我将光标的图像粘贴到屏幕截图中,但是当我完成录制视频时出现错误播放时

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

screen_size = pyautogui.size()
FPS = 11.0

def recorder(screen_size, FPS):

    fourcc = cv2.VideoWriter_fourcc(*"XVID")
    video = cv2.VideoWriter("VIDEO.avi", fourcc, FPS, (screen_size))

    start = input("RECORD ")

    if start == "y":

        ruta_actual =  os.getcwd()
        print(f"ruta actual: {ruta_actual}")

        while True:

                if keyboard.is_pressed("p"):
                    break

                # CURSOR POSITION
                screenshot_img = pyautogui.screenshot()
                x, y = pyautogui.position()

                cursor_img = Image.open(f"{ruta_actual}\resources\cursor_state0.png").convert("RGBA")

                complete_img = Image.new('RGBA', (screen_size), (0, 0, 0, 0))
                complete_img.paste(screenshot_img, (0, 0))
                complete_img.paste(cursor_img, (x, y), cursor_img)

                data = np.array(complete_img)

                video.write(data)

        video.release()

if __name__ == "__main__":
    grabar = recorder(screen_size, FPS)

您正在将 RGBA 图像格式写入 cv2.VideoWriter,而预期格式为 BGR

data = np.array(complete_img)替换为:

data = cv2.cvtColor(np.array(complete_img), cv2.COLOR_RGBA2BGR)

在我的机器上,我在播放视频时没有遇到任何错误(我得到的是黑色视频),所以可能是第二个问题。
如果还是不行,试试把编解码器换成cv2.VideoWriter_fourcc(*"MJPG").