我怎样才能保持时间的一致性

2024-04-20 14:48:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在通过编写大量无用的代码来训练我的python能力,今天我尝试在控制台中使用ASCII艺术打印Bad apple,就像一个人一样,我做的一切都很好,直到我必须对打印进行计时,以使它们在3分52秒内结束,并保持一致的帧速率。我试着在两张照片之间加上一个time.sleep(),希望这一切都能神奇地起作用,但显然没有

我定制了一个版本的git https://github.com/aypro-droid/image-to-ascii来将帧转换为ASCII艺术,并使用https://pypi.org/project/opencv-python/将视频转换为帧

这是我的密码:

import time
frames = {}
#saving each .txt frame on a dict
for i in range(6955):
    f = open("Frames-to-Ascii/output/output{0}.txt".format(i), "rt")
    frames['t{0}'.format(i)] = f.read()
    f.close()
#start "trigger"
ini = input('start(type anything): ')
start = time.time()
#printing the 6954 frames from the dict
for x in range(6955):
    eval("print(frames['t{0}'])".format(x))
    #my attempt at timing
    time.sleep(0.015)
end = time.time()
#calculating how much time the prints took overall, should be about 211.2 seconds evenly distributed to all the "frames"
print(end-start)

框架示例: here

我正试图将照片与视频完美匹配,以便以后在其他地方使用,有什么提示吗


1条回答
网友
1楼 · 发布于 2024-04-20 14:48:09

我的理解是,您需要以给定的恒定速率打印帧? 如果是,则需要计算用于打印的时间,然后睡眠延迟减去打印时间。比如:

for x in range(6955):
    start = time.time()
    print("hips")
    end = time.time()
    time.sleep(0.5-(end-start))

因此,循环运行(大约)需要0.5秒。(根据需要更改相应的值)

当然,如果一次打印花费的时间超过延迟时间,您需要找到另一种策略:例如跨过下一帧,等等

相关问题 更多 >