0

我已经编写了一个代码来使用 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))
 
4

1 回答 1

0

构造函数的第三个参数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几秒钟以上),那么您可能需要降低帧速率或分辨率。

于 2020-07-26T09:41:34.017 回答