1

I am trying to make a screen recording script with python. This is what I have so far:

import cv2
import numpy as np
import pyautogui
import time

img = pyautogui.screenshot()
img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter("video.mp4", fourcc, 60.0, (1680, 1050))

t1 = time.time()
for i in range(0, 300):
    img = pyautogui.screenshot()
    image = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
    out.write(image)
t2 = time.time()

print(t2-t1)
out.release()

Adding a delay doesn't help much either. I have tried time.sleep(1/60) because the framerate is 60 FPS.

This code should make a 5 second long video (which it does) but to actually take 300 frames (screenshots) it takes 21 seconds, making the video really fast. I assume this could be solved if the frame-catching procedure was way faster. I have timed on how long it takes pyautogui.screenshot() and PIL.ImageGrab.grab() to take a screenshot, both roughly around 0.05 seconds. The current "solution" I have is to lower the framerate to somewhere around 10 fps but then it becomes really choppy. How can I fix this?

ammarsys
  • 121
  • 2
  • 7
  • You may use [FFmpeg](https://trac.ffmpeg.org/wiki/Capture/Desktop) for screen capturing instead of OpenCV. The [following](https://stackoverflow.com/questions/67276793/output-always-corrupt-from-ffmpeg-using-selenium-python) post is not the best example, just the one I answered. – Rotem May 03 '21 at 20:51
  • currently you are waiting 1/60 + time for capturing + time for encoding&writing. If you are sure that your source delivers exactly 60 fps you should not sleep at all, because VideoCapture will have to wait for the camera anyways. However, it could happen that your processing is still slower than fps. – Micka May 04 '21 at 05:06

0 Answers0