0

I am trying to make a project to detect face mask using OpenCV, HaarCascade and Pyttsx3. The flow of the project is when mouth is not detected on a face then it should speak "face mask detected" else it should say "please wear face mask". The problem that i am facing is that when it speaks for the first time the frame freezes and the loop ends there. Please help me fix the issue.

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

Community
  • 1
  • 1

1 Answers1

0

To answer it v shortly, you need to use threading. This is the docs. https://docs.python.org/3/library/threading.html. You can append your count to a list, and when theres no mask, do a count + 1. If your count_list >=1, use threading to call the voice.

Jonathan
  • 424
  • 4
  • 14