pythonopencvaudiopyaudiorecording

Video Recording is too fast in opencv python


I'm capturing my screen using OpenCV on windows. It works fine but when I try to play my captured video it plays too fast. i.e. I capture from video for 60 seconds but when I play it OpenCV recorded longer and sped up to fit the additional times content into 60 seconds of video i.e. sped up

import cv2
import numpy as np
import pyautogui

time = 10
# display screen resolution, get it using pyautogui itself
SCREEN_SIZE = tuple(pyautogui.size())
# define the codec
fourcc = cv2.VideoWriter_fourcc(*"XVID")
# frames per second
fps = 30.0
# create the video write object
out = cv2.VideoWriter("output.avi", fourcc, fps, (SCREEN_SIZE))

for i in range(int(time * fps)):
    # make a screenshot
    img = pyautogui.screenshot()
    # convert these pixels to a proper numpy array to work with OpenCV
    frame = np.array(img)
    # convert colors from BGR to RGB
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    # write the frame
    out.write(frame)

# make sure everything is closed when exited
cv2.destroyAllWindows()
out.release()

I tried different fps which did not change much. Please let me know why this happens. Any answers and help welcome.


Solution

  • you need to wait in-between taking screen shots. There may be a more ideal solution, but this would probably suffice:

    from time import time, sleep
    record_time = 10 #don't overwrite the function we just imported
    start_time = time()
    for i in range(int(record_time * fps)):
        # wait for next frame time
        next_shot = start_time + i/fps
        wait_time = next_shot - time()
        if wait_time > 0:
            sleep(wait_time)
        # make a screenshot
        img = pyautogui.screenshot()
        ...
    

    notes