我在 Windows 上使用 OpenCV 捕獲我的螢屏。它作業正常,但是當我嘗試播放我捕獲的視頻時,它播放得太快了。即我從視頻中捕獲了 60 秒,但是當我播放它時,OpenCV 錄制的時間更長并加快了速度,以將額外的時間內容放入 60 秒的視頻中,即加快了速度
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()
我嘗試了不同的fps,但變化不大。請讓我知道為什么會這樣。歡迎任何答案和幫助。
uj5u.com熱心網友回復:
您需要在拍攝螢屏截圖之間等待。可能有更理想的解決方案,但這可能就足夠了:
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()
...
筆記
time.time的解析度取決于作業系統。確保你得到一個帶小數秒的數字。否則,您可能需要使用類似time.perf_counteror的東西time.time_ns。- 這不能使回圈運行得更快,只會變慢。如果您不能足夠快地獲取幀,則錄制將持續超過
record_time幾秒鐘,并且播放似乎會“加快”。解決這個問題的唯一方法是找到一種更快的方法來獲取螢屏截圖(比如降低解析度?)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/531075.html
