首页 > 解决方案 > 如何在 pyttsx3 中使用 OpenCV

问题描述

我正在尝试制作一个使用 OpenCV、HaarCascade 和 Pyttsx3 检测面罩的项目。该项目的流程是当没有在脸上检测到嘴巴时,它应该说“检测到口罩”,否则应该说“请戴口罩”。我面临的问题是,当它第一次说话时,框架冻结并且循环在那里结束。请帮我解决问题。

import cv2
import pyttsx3

camera=cv2.VideoCapture(0)
face_cascade=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
mouth_cascade=cv2.CascadeClassifier('haarcascade_mcs_mouth.xml')
sum=0
count=0
display=""
color=(0, 0, 255)
#function to use text to speech
def speak(display): #here the issue is it speaks first time and then programs ends
    engine = pyttsx3.init()
    engine.say(display)
    engine.runAndWait()
    engine.stop()

while True:
    cap, frame = camera.read()
    gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces=face_cascade.detectMultiScale(gray,1.3,1)
    font = cv2.FONT_HERSHEY_SIMPLEX
    cv2.putText(frame, display, (50, 50), font, 1, color, 2, cv2.LINE_4)
    #loop to create rectangle around faces and finding the roi to apply mouth detection 
    for (x,y,w,h) in faces:
        cv2.rectangle(frame, (x,y),(x+w,y+h),(255,0,0),5)
        roi_gray = gray[y:y + h, x:x + w]
        roi_color = frame[y:y + h, x:x + w]
        mouth=mouth_cascade.detectMultiScale(roi_gray,1.7,6)
    for (mx, my, mw, mh) in mouth:
        cv2.rectangle(roi_color, (mx, my), (mx + mw, my + mh), (0, 255, 0), 2)
    cv2.imshow("Test",frame)
    w=cv2.waitKey(1)
    #if mouth is not detected in face then person is wearing face mask
    if len(mouth) == 0:
        display="Mask Detected"
        color=(0, 255, 0)
        speak(display)
    else:
        display="Please Wear Face Mask"
        color = (0, 0, 255)
        speak(display)
    if w==ord('q'):
        break

标签: python-3.xopencvopencv-pythonhaar-classifierpyttsx3

解决方案


要尽快回答 v,您需要使用线程。这是文档。https://docs.python.org/3/library/threading.html. 您可以将您的附加count到列表中,当没有掩码时,执行count + 1. 如果你的count_list >=1,使用线程来调用语音。


推荐阅读