D
D
Devil_Evil20212021-05-10 13:32:01
Python
Devil_Evil2021, 2021-05-10 13:32:01

How to stop the execution of the program after some time?

I want to authorize by face (through a webcam), but if the face was not found within, for example, 10 seconds, then the program issued a corresponding message and completed the face search, that is, returning to the authorization window.

1. How to display this window after 10 seconds?
Now 10 seconds pass and a window appears simultaneously with an error:

QObject::setParent: Cannot set parent, new parent is in a different thread

2. Как получить доступ к переменной cam из FaceUnlock в NoFace, чтобы завершить работу программы(поиска лиц) спустя 10 секунд?
Или может быть можно вызвать cam.release спустя 10 секунд в FaceUnlock? Только time.sleep останавливает программу, а мне нужно, чтобы без остановок, а с многопоточностью не получается пока что.
from threading import Timer

def FACE_UNLOCK(self):

        recognizer = cv2.face.LBPHFaceRecognizer_create()
        recognizer.read('trainer/trainer.yml')
        cascadePath = "haarcascade_frontalface_default.xml"
        faceCascade = cv2.CascadeClassifier(cascadePath);

        font = cv2.FONT_HERSHEY_SIMPLEX

#iniciate id counter
        id = 0

        face_un = ['Admin']

        cam = cv2.VideoCapture(0)

        w1 = cam.get(cv2.CAP_PROP_FRAME_WIDTH)
        h1 = cam.get(cv2.CAP_PROP_FRAME_HEIGHT)
  
    
# Define min window size to be recognized as a face
        minW = 0.1*w1
        minH = 0.1*h1 

        Timer(10, self.NoFace).start() #функция таймера на 10 секунд

        while(cam.isOpened()):

            ret, img =cam.read()    

            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            faces = faceCascade.detectMultiScale( 
                gray,
                scaleFactor = 1.2,
                minNeighbors = 5,
                minSize = (int(minW), int(minH)),
                )
        

            for(x,y,w,h) in faces:

                cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)

                id, confidence = recognizer.predict(gray[y:y+h,x:x+w])

            # Check if confidence is less them 100 ==> "0" is perfect match 
                if (confidence < 100):
                    id = face_un[0]
                    confidence = "  {0}%".format(round(100 - confidence))
                    cam.release()
                    self.FProj = ProjectPrg()
                    self.FProj.show()
                    Main.setVisible(self, False)
     
                else:
                    id = "unknown"
                    confidence = "  {0}%".format(round(100 - confidence))

                cv2.putText(img, str(id), (x+5,y-5), font, 1, (255,255,255), 2)
                cv2.putText(img, str(confidence), (x+5,y+h-5), font, 1, (255,255,0), 1) 
            cv2.imshow('Face Unlock',img) 
            k = cv2.waitKey(10) & 0xff # Press 'ESC' for exiting video
            if k == 27:
                break         
              
        cam.release()
        cv2.destroyAllWindows()

def NoFace(self):
        msg1 = QMessageBox(self)
        msg1.about(self, "Ошибка", "Программа не обнаружила лицо администратора.\nВ авторизации по лицу отказано, используйте пароль и логин.")

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-05-10
@Devil_Evil2021

Just add a timeout parameter to FACE_UNLOCK(), capture the current time before entering the while(cam.isOpened()) loop, and inside the loop check if enough time has elapsed or not.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question