我正在尝试处理视频,并将视频转换为灰度图像,并对视频的每一帧进行实时像素处理,因为它们正在使用OpenCV的imshow()处理并显示在屏幕上。我遇到的问题是每个帧需要花费不同的时间来处理,并且帧速率不是恒定的,因为视频在处理和显示时似乎在随机时间出现滞后。因此,处理后的视频实际上无法实时处理和播放。我希望它在处理过程中显示处理后的视频而没有任何滞后时间,因此它看起来像是实时视频,而不是随机斑点中的抖动,因为来自视频处理计算的滞后时间使其不理想。
我在那里进行了一些调试,以显示每帧花费的时间:
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
如您所见,它是不一致的。我希望此帧每次都与正在处理的视频完全相同。它不必尽可能快,每帧的一致性比最快的视频处理时间更重要。我在20秒内处理了1205帧,但是这些帧的时间不一致,因此在视频中显得不方便
答案 0 :(得分:1)
在视频游戏编程中,我们拥有锁定帧速率的技术
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...
您可以看到每个处理之间的时间差为500ms(2 FPS)。您可以将FPS提高到任意水平,但如果处理时间超过一帧(1 / FPS秒)。该代码仍然会导致延迟。