[英]How to call a function only once and wait for 5 seconds before calling again inside while loop- Python
当在实时摄像头源上检测到微笑时,我正在尝试捕获图像并播放歌曲。 我创建了一个单独的线程来播放完整的歌曲并使用多线程保存图像,因为在播放歌曲时帧会卡住。 我面临的问题是,在无限 while 循环内,多线程 function 在一秒钟内被多次调用,导致歌曲重叠并保存许多图像。 有没有更好的方法来调用 function 一次并等待几秒钟(正好 5 秒)直到歌曲完成而不中断/暂停 while 循环? 这是我处理过的代码:
import cv2
import datetime
import threading
from playsound import playsound
def play_save(save_img):
print("Saving Image")
time_stamp = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
file_name = f'selfie-{time_stamp}.png'
cv2.imwrite(file_name, save_img)
print("Playing Song")
playsound("Happy_birthday.mp3")
def main():
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
smile_cascade = cv2.CascadeClassifier('haarcascade_smile.xml')
cap = cv2.VideoCapture(0)
while True:
ret, img = cap.read()
frame = img.copy()
if not ret:
break
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
roi_gray = gray[y:y + h, x:x + w]
roi_color = img[y:y + h, x:x + w]
smile = smile_cascade.detectMultiScale(roi_gray, 1.3, 25)
for x1, y1, w1, h1 in smile:
cv2.rectangle(img, (x1, y1), (x1 + w1, y1 + h1), (0, 0, 255), 2)
multithread = threading.Thread(target=play_save, args=(frame,))
multithread.start()
cv2.imshow('Smile Birthday', img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
一个想法是使用 UTC-Time 来检查它。 你可以这样检查:
import time
time_function_done = None
while True:
#Do some shit
if (time_function_done + 5) < time.time():
time_function_done = time.time()
#Do your function
#Do some other shit
如果找不到直接的解决方案,请制定解决方法。 希望这可以帮助:))
import time
time.sleep(5) # Sleep for 5 seconds
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.