Home > database >  Python cv2: Video does not play
Python cv2: Video does not play

Time:11-06

I want to make a screen recorder and that the cursor appears in each frame of the video, for this I paste the image of the cursor in the screenshot, but when I finish recording the video it comes out with an error when playing it.

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)

CodePudding user response:

You are writing RGBA image format to cv2.VideoWriter, while the expected format is BGR.

Replace data = np.array(complete_img) with:

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

In my machine, I am not getting any error playing the video (I am getting black video), so there might be second problem.
If it still doesn't work, try replacing the codec to cv2.VideoWriter_fourcc(*"MJPG").

  • Related