我写了一个程序,当检测到人脸时会发出警告声(播放音频文件)
但是,当检测条件被触发时,声音文件总是会在 10~30 秒后开始播放。
如果把它从条件句中去掉,作为背景音乐播放,就没有问题。请问怎么解决?
谢谢!
我用来播放声音的代码:
winsound.PlaySound('1.wav', winsound.SND_FILENAME|winsound.SND_ASYNC)
完整代码:
# -*- coding: utf-8 -*-
import dlib
import cv2
import imutils
import winsound
import os
import multiprocessing
import winsound
import time
from winsound import SND_ASYNC
import pygame
from pygame import mixer
#chose camera
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
#change size
cap.set(cv2. CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2. CAP_PROP_FRAME_HEIGHT, 360)
#Get the default face detector
detector = dlib.get_frontal_face_detector()
#Load 68 feature point models according to the shape_predictor method, this method is a detector for facial expression recognition
predictor = dlib.shape_predictor( 'shape_predictor_68_face_landmarks.dat')
#When the camera is turned on, each frame is detected
#pygame.mixer.init()
#mixer.music.load('incoming.mp3')
#mixer.music.play(-1)
#winsound.PlaySound('incoming.wav', winsound.SND_FILENAME| winsound.SND_ASYNC )
while(cap.isOpened()):
#Read frame information
ret, frame = cap.read()
#Detect faces
face_rects, scores, idx = detector.run(frame, 0)
#Retrieve the detection result
for i, d in enumerate(face_rects):
x1 = d.left()
y1 = d.top()
x2 = d.right()
y2 = d.bottom()
text = " %2.2f ( %d )" % (scores[i], idx[i])
#Draw a rectangular area for detecting faces
cv2.rectangle(frame, (x1, y1), (x2, y2), ( 0, 255, 0), 4, cv2. LINE_AA)
#Mark the face detection score and face direction sub-detector number
cv2.putText(frame, text, (x1, y1), cv2. FONT_HERSHEY_DUPLEX,
0.7, ( 255, 255, 255), 1, cv2. LINE_AA)
#play sound
if scores[i]>0.3 and idx[i]==0 :
print(text)
#pygame.mixer.pre_init(48000, 16, 2, 4096)
winsound.PlaySound('incoming.wav', winsound.SND_FILENAME| winsound.SND_ASYNC )
#Output to screen
cv2.imshow( "Face Detection", frame)
#If you press the ESC key, you exit
if cv2.waitKey( 10) == 27:
break
#Free memory
cap.release()
#Close all windows
cv2.destroyAllWindows()
和这里的 gprof2dot