如何解决如何在python中闭上眼睛5秒后播放警报?
我写了一个司机安全的代码,但是我不知道如何在闭眼或他们向左或向右看5秒后播放警报。 这些是我需要放置它们的条件:
if EAR < 0.26:
cv2.putText(frame,"Alert!",(20,100),cv2.FONT_HERShey_SIMPLEX,3,(0,255),4)
print("X")
if gaze_ratio <= 1:
cv2.putText(frame,"RIGHT",(50,font,2,3)
new_frame[:] = (0,255)
elif 1 < gaze_ratio < 1.7:
cv2.putText(frame,"CENTER",3)
else:
new_frame[:] = (255,0)
cv2.putText(frame,"LEFT",3)
解决方法
我没有足够的声誉来发表评论: 请注意,您在问题中的缩进肯定是错误的。 您可能需要修复它并明确指出您希望在接下来的 5 秒内触发警报的位置。
有关您的应用的更多上下文、您的主循环播放音频的方式可能需要提供正确的答案。
但是没有上下文,我先试一试:
文件头部
import threading
def play_sound():
# add here the actual code playing the sound
在您想要开始警报的地方
if shall_alert_in_5_seconds: # replace with the appropriate if statement
timer = threading.Timer(5,play_sound)
timer.start()
另一个稍微复杂的解决方案,您可以尝试: 但这完全取决于您使用什么来播放某些声音。
这使用一个全局计时器和一个线程锁来避免并发问题
只要触发了一个计时器,它就不会触发另一个计时器。 还有一个函数,就是
文件头部
import threading
from threading import Lock
timer = None # use only one global timer
lock = Lock()
def play_sound():
print("start playing sound") # comment/remove after debugging
# add here the actual code playing the sound
print("end playing sound") # comment/remove after debugging
with lock:
if timer is not None:
timer = None
print("timer cleared") # comment/remove after debugging
def trigger_timer():
print("shall trigger timer?") # comment/remove after debugging
with lock:
if timer is None:
timer = threading.Timer(5,play_sound)
timer.start()
print("shaltimer triggered?") # comment/remove after debugging
def cancel_timer():
print("shall cancel timer?") # comment/remove after debugging
with lock:
if timer is not None:
timer.cancel()
timer = None
print("timer canceled") # comment/remove after debugging
现在在你想在 5 秒内开始声音的每个地方调用:
trigger_timer()
每当您检测到事件时,就会告诉您不想再播放您调用的声音。
cancel_timer()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。