0

我有与 plc 通信的视频处理代码。在无限循环中,我需要一个计时器/计数器来执行命令。代码如下所示:

while True: 
    if(condition1): 
        #do something

    elif(condition2): 
        #do another thing

    elif(condition3): 
        #do another thing

    elif(condition_10s_passed): 
        print("You have waited too long")

在这里,我无法time.sleep()从 time 或root.after()tkinter 实现,因为它们停止了我不想要的 while 循环。我检查threading.timer()但也无法实现它。

我使用来自 mediapipe 的姿势检测算法,并在屏幕上显示视频。我也找到了一个解决方案,但它导致视频中的 fps 下降,所以我要求一个更好的解决方案。

我的解决方案是这样的:我定义了old_time除内部之外的所有地方,elif在其中我检查了经过时间的条件。然后我将当前时间与 old_time 之间的差异来测量经过的时间。

while True:
    old_time=time.time() 

    if(condition1): 
        old_time=time.time()
        #do something 

    elif(condition2): 
        old_time=time.time()
        #do another thing

    elif(condition3): 
        old_time=time.time()
        #do another thing

    elif (time.time()-oldtime)>10: 
        print("You have waited too long")

fps 下降的原因可能是其他原因,但它是在我实施此解决方案后开始的。我不是优化代码方面的专家,我需要知道 fps 问题是否不是由于太多 old_time 定义造成的。

注意:这是我的第一个问题,我愿意接受关于我的问题的评论(它的标题、内容、定义等)

4

1 回答 1

0

我找到了解决方案。我使用 time.sleep() 但在另一个线程中不要中断 while 循环。

#5 seconds timer
def timer():
   global limit_time
   limit_time = False
   time.sleep(5)
   limit_time = True

#Starting the timer in another thread when condition is satisfied
if("condition to start timer"):
   thread1 = Thread(target=timer)
   thread1.start()

在这里,当条件满足时,timer会调用等待 5 秒的函数,然后将变量更改limit_timeTrue。然后在代码中我知道通过检查变量经过了 5 秒limit_time

于 2021-09-08T07:55:05.710 回答