如何在cv2中增加屏幕录像机的fps

How to increase the fps of screen recorder in cv2

我写了一个代码来使用 python 录制屏幕录像机但是当我看到输出时我发现它的 fps 很低。有没有比我更好的代码来增加 fps屏幕录像机。 如果是,请回复。 这是我的代码:-

import cv2
import numpy as np
import pyautogui
import datetime
# display screen resolution, get it from your OS settings
SCREEN_SIZE = (1366, 768)
# define the codec
fourcc = cv2.VideoWriter_fourcc(*"XVID")
# create the video write object
now = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
out = cv2.VideoWriter("screen recorder"+now+".avi", fourcc, 5.0, (SCREEN_SIZE))
while True:
    img = pyautogui.screenshot()
    frame = np.array(img)
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    out.write(frame)
    cv2.imshow("screenshot", frame)
    # if the user clicks q, it exits
    if cv2.waitKey(1) == ord("q"):
        break
cv2.destroyAllWindows()
out.release()
img = pyautogui.screenshot(region=(0, 0, 300, 400))
 

cv2.VideoWriter 构造函数的第三个参数是帧速率 (https://docs.opencv.org/3.4/dd/d9e/classcv_1_1VideoWriter.html#ac3478f6257454209fa99249cc03a5c59)。目前,您已将其设置为 5.0。例如,对于 30 fps,将 VideoWriter 实例化为:

out = cv2.VideoWriter("screen recorder"+now+".avi", fourcc, 30.0, (SCREEN_SIZE))

编辑:为了以正确的帧率读取图像,我们可以使用 waitKey 函数暂停 while 循环。我们可以像这样重写 OP 的代码:

import cv2
import numpy as np
import pyautogui
import datetime
import time
# display screen resolution, get it from your OS settings
SCREEN_SIZE = (1366, 768)
FRAME_RATE = 30.0  # desired frame-rate
# define the codec
fourcc = cv2.VideoWriter_fourcc(*"XVID")
# create the video write object
now = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
out = cv2.VideoWriter("screen recorder"+now+".avi", fourcc, FRAME_RATE, (SCREEN_SIZE))
while True:
    st = time.time()  # collect start time
    img = pyautogui.screenshot()
    frame = np.array(img)
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    out.write(frame)
    cv2.imshow("screenshot", frame)
    en = time.time()  # collect end time
    # calculate time to wait before next frame:
    delay = max(0, (1 / FRAME_RATE - (en - st)) * 1000)  
    # if the user clicks q, it exits
    if cv2.waitKey(delay) == ord("q"):
        break
cv2.destroyAllWindows()
out.release()
img = pyautogui.screenshot(region=(0, 0, 300, 400))

注意:如果收集帧太慢(需要超过 1 / FRAMERATE 秒),那么您可能需要降低帧速率或分辨率。