如何以恒定的帧速率处理视频帧?



我正在尝试处理视频并将视频转换为灰度,并在视频的每一帧上实时进行一些像素操作,因为它正在使用 imshow(( 和 OpenCV 在屏幕上进行处理和显示。我遇到的问题是,每一帧需要不同的时间来处理,并且帧速率不是恒定的,因为视频在处理和显示时似乎随机滞后。因此,处理后的视频实际上并没有实时处理和播放。我希望它在处理过程中显示处理后的视频,没有任何延迟时间,这样它看起来是一个实时视频,而不是随机点的抖动,因为视频处理计算的延迟时间使其不太理想。

我在那里进行了一些调试,以显示每帧所需的时间:

Time this frame: 0.015553
Time this frame: 0.015620
Time this frame: 0.015673
Time this frame: 0.031236
Time this frame: 0.031249
Time this frame: 0.031237
Time this frame: 0.031247
Time this frame: 0.031283
Time this frame: 0.031265
Time this frame: 0.015629
Time this frame: 0.015502

这是非常基本的代码。

//capture the video file
//get each frame
//while capture is opened
//convert each frame to greyscale and do some minor video processing code
//cv2.imshow("window", VideoInGreyscale)
//repeat until video file is completely processed and video ends

如您所见,它是不一致的。我希望每次此帧都与正在处理的视频完全相同。它不必尽可能快,每帧的一致性比最快的视频处理时间更重要。我在 1205 秒内处理 20 帧,但帧计时不一致,因此在视频中显得滞后

在视频游戏编程中,我们有这种技术来锁定帧速率

import time
processing = True
frames_per_second = 2
time_in_frame = (1 / frames_per_second) * 1000 #milliseconds
def get_cur_millis():
return int(round(time.time() * 1000))
def process():
print("processing...")
while processing:
start_time = get_cur_millis()
print("current time is {}".format(get_cur_millis()))
process()
time_elapsed = get_cur_millis() - start_time
# Sleep until till the next frame should run.
time.sleep(max((time_in_frame - time_elapsed) / 1000, 0))

当我运行它时,输出是:

current time is 1565329457172
processing...
current time is 1565329457675
processing...
current time is 1565329458176
processing...
current time is 1565329458678
processing...
current time is 1565329459179
processing...
current time is 1565329459681
processing...
current time is 1565329460181
processing...

您可以看到每次处理之间的时间差为 500 毫秒 (2 FPS(。您可以将 FPS 提高到您喜欢的任何内容,但如果您的处理时间超过一帧(1/FPS 秒(。此代码仍会导致滞后。

最新更新