简体   繁体   English

While True 循环在 While True 循环内

[英]while True loop inside a While True loop

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.基本上,每次检测到我的脸时,我都需要蜂鸣器和 LED 播放/点亮,但到目前为止它只播放一次。 eg.例如。 I show my face and it plays "signed in" and the light turns on for 3 seconds once and it stops working.我露出我的脸,它播放“已登录”,灯亮了 3 秒钟,它停止工作。

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.关于项目:我们在 ras pi 上使用 usb 摄像头来识别人脸并“解锁门”,当前打开 LED 3 秒钟,每次识别到某人的脸时,扬声器都会说“已登录”。 SQL is for attendance taking done by my classmate so I can't really explain it. SQL 是我同学做的考勤,所以我无法解释。

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()

The inner loop has an unconditional break , and so never iterates more than once.内部循环有一个无条件的break ,因此从不重复多次。 The outer loop has no break , so never stops.外循环没有break ,所以永远不会停止。

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 .第一次运行后,您将值分配给变量currentname ,并且在循环的下一次迭代中, if currentname: = name:条件将为False Try resetting \ deleting the currentname variable before the break statement尝试在break语句之前重置 \ 删除 currentname 变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM