为什么在循环外出现语法错误“ break”?

时间:2019-11-23 09:00:11

标签: python

我有这段代码,但我不知道为什么会收到错误Break outside loop。你能帮我吗?

def TrackImage():
    recognizer = cv2.face_LBPHFaceRecognizer.create()
    recognizer.read('C:/Users/Jin/Anaconda3/envs/final/TrainingImageLabel/Trainner.yml')
    harcascadePath = ("C:/Users/Jin/Desktop/python opencv/opencv/build/etc/haarcascades/haarcascade_frontalface_default.xml")
    faceCascade = cv2.CascadeClassifier(harcascadePath)
    df=pd.read_csv('StudentDetails/studentDetails.csv')
    cam=cv2.FONT_HERSHEY_SIMPLEX
    col_names = ['Id','Name','Date','Time']
    attendance = pd.DataFrame(Columns = col_names)
    while True:
        ret, img = cam.read()
        gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
        faces = detector.detectMultiScale(gray,1.3,5)
        for (x,y,w,h) in faces:
            cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
            Id, conf = recognizer.predict(gray[y:y+h, x:x+w])
            if (conf < 50):
                ts = time.time()
                date=datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
                timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M,%S')
                aa = df.loc[df['Id'] == Id]['Name'].values
                tt=str(Id)+"-"+aa
                attendance.loc[len(attendance)] = [Id,aa,date,timeStamp]
            else:
                Id='Unknown'
                tt=str(Id)
                if(conf>75):
                    noOfFile=len (os.listdir("ImagesUnknown"))+1
                    cv2.imwrite("ImagesUnknown\Image"+str(noOfFile)+".jpg",im[y:y+h,x:x+w])
                cv2.putText(im,str(tt),(x,y+h), font, 1 ,(255,255,255),2)
    attendance= attendance.drop_duplicates(subset=['Id'],keep='first')
    cv2.imshow('im',im)
    if(cv2.waitKey(1)==ord('q')):
        break

2 个答案:

答案 0 :(得分:1)

因为break仅用于强制退出循环。在您发布的代码中,您使用break退出了if条件,这是非法的。您可以使用exit

Break documentation

答案 1 :(得分:0)

检查代码的最后两行。 break不在任何循环中。

将其放入特定的循环中(如果需要),否则将其删除。