Home > Net >  while True loop inside a While True loop
while True loop inside a While True loop

Time:12-28

Basically I need the buzzer and LED to play/light up every time it detects my face but it only does it once as of now. eg. I show my face and it plays "signed in" and the light turns on for 3 seconds once and it stops working.

About the project: we are using a usb camera on a ras pi to recognize faces and "unlock a door" currently turning on an LED for 3 seconds and a speaker will say "signed in" every time it someone's face is recognized. SQL is for attendance taking done by my classmate so I can't really explain it.

from imutils.video import VideoStream
from imutils.video import FPS  
import face_recognition
import imutils                                                                                   
import pickle                       
import time               
import cv2
import mysql.connector
from datetime import datetime,date
from playsound import playsound
from gpiozero import LED 

from time import sleep


db = mysql.connector.connect(
    host="localhost",
    user="User",
    passwd="passwd",
    database="attendancesystem")

cursor = db.cursor()    

identified.
currentname = "unauthorised"
train_model.py
encodingsP = "encodings.pickle"

print("[INFO] loading encodings   face detector...")
data = pickle.loads(open(encodingsP, "rb").read())

to my laptop
vs1 = VideoStream(src=0,framerate=30).start()
time.sleep(2.0)


# loop over frames from the video file stream
while True:
    # grab the frame from the threaded video stream and resize it
    # to 500px (to speedup processing)
    frame = vs1.read()
    frame = imutils.resize(frame, width=500)
    # Detect the fce boxes
    boxes = face_recognition.face_locations(frame)
    # compute the facial embeddings for each face bounding box
    encodings = face_recognition.face_encodings(frame, boxes)
    names = []

    # loop over the facial embeddings
    for encoding in encodings:
        # attempt to match each face in the input image to our known
        # encodings
        matches = face_recognition.compare_faces(data["encodings"],
            encoding)
        name = "Unauthorised" #if face is not recognized, then print Unknown

        # check to see if we have found a match
        if True in matches:
            # find the indexes of all matched faces then initialize a
            # dictionary to count the total number of times each face
            # was matched
            matchedIdxs = [i for (i, b) in enumerate(matches) if b]
            counts = {}

            # loop over the matched indexes and maintain a count for
            # each recognized face face
            for i in matchedIdxs:
                name = data["names"][i]
                counts[name] = counts.get(name, 0)   1

            # determine the recognized face with the largest number
            # of votes (note: in the event of an unlikely tie Python
            # will select first entry in the dictionary)
            name = max(counts, key=counts.get)

            #If someone in your dataset is identified, print their name on the screen
            if currentname != name:
                currentname = name
                print(currentname)
                #results = ("SELECT a_s.Admin_no,a_s.Name,a.clock_in FROM authorised_students a_s JOIN attendance a ON a_s.Admin_no = a.Admin_no")
                #cursor.execute(results])
                #for x in cursor:/';
                #   print(x)
                t = datetime.now()
                time = t.strftime("%H:%M:%S")
                date = date.today()
                cursor.execute("INSERT INTO Sign_in (admin_no, Date, Clock_in) VALUES (%s,%s,%s)",(currentname,date,time))
                db.commit()
                while True:
                #Buzzer
                    playsound('/home/pi/Desktop/Sound effects/Signed in.mp3')
                #LED 
                    red = LED(17)
                    red.on()
                    sleep(3)
                    red.off()
                    break

        # update the list of names
        names.append(name)

    # loop over the recognized faces
    for ((top, right, bottom, left), name) in zip(boxes, names):
        # draw the predicted face name on the image - color is in BGR
        cv2.rectangle(frame, (left, top), (right, bottom),
            (0, 255, 225), 2)
        y = top - 15 if top - 15 > 15 else top   15
        cv2.putText(frame, name, (left, y), cv2.FONT_HERSHEY_SIMPLEX,
            .8, (0, 255, 255), 2)

    # display the image to our screen
    cv2.imshow("Facial Recognition is Running", frame)
    key = cv2.waitKey(20) & 0xFF
    


    # quit when 'q' key is pressed
    if key == ord("q"):
        break

    # update the FPS counter
    #fps.update()

#hardware interrupt 



cv2.destroyAllWindows()
vs1.stop()

CodePudding user response:

The inner loop has an unconditional break, and so never iterates more than once. The outer loop has no break, so never stops.

CodePudding user response:

After the first run, you assign the value to the variable currentname, and on the next iterations of the loop, the if currentname! = name: condition will be False. Try resetting \ deleting the currentname variable before the break statement

  • Related