繁体   English   中英

我正在使用 LBPH 算法,但我的面部识别和出勤出现此错误“raise KeyError(key) from err KeyError: 'Id'” function

[英]I am using LBPH algorithm but I got this error “raise KeyError(key) from err KeyError: 'Id' ” for my face recognize and attendance function

这是我的面部识别和出勤代码:

import datetime
import os
import time

import cv2
import pandas as pd


#-------------------------
def recognize_attendence():

recognizer = cv2.face.LBPHFaceRecognizer_create()  
# cv2.createLBPHFaceRecognizer()
recognizer.read("TrainingImageLabel"+os.sep+"Trainner.yml")
harcascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(harcascadePath)
df = pd.read_csv("StudentDetails"+os.sep+"StudentDetails.csv")
font = cv2.FONT_HERSHEY_SIMPLEX
col_names = ['Id', 'Name', 'Date', 'Time']
attendance = pd.DataFrame(columns=col_names)

# Initialize and start realtime video capture
cam = cv2.VideoCapture(0, cv2.CAP_DSHOW)
cam.set(3, 640)  # set video width
cam.set(4, 480)  # set video height
# Define min window size to be recognized as a face
minW = 0.1 * cam.get(3)
minH = 0.1 * cam.get(4)

while True:
    ret, im = cam.read()
    gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(gray, 1.2, 5,minSize = (int(minW), int(minH)),flags =           cv2.CASCADE_SCALE_IMAGE)
    for(x, y, w, h) in faces:
        cv2.rectangle(im, (x, y), (x+w, y+h), (10, 159, 255), 2)
        Id, conf = recognizer.predict(gray[y:y+h, x:x+w])

        if conf < 100:

            aa = df.loc[df['Id'] == Id]['Name'].values
            confstr = "  {0}%".format(round(100 - conf))
            tt = str(Id)+"-"+aa


        else:
            Id = '  Unknown  '
            tt = str(Id)
            confstr = "  {0}%".format(round(100 - conf))

        if (100-conf) > 67:
            ts = time.time()
            date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
            timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
            aa = str(aa)[2:-2]
            attendance.loc[len(attendance)] = [Id, aa, date, timeStamp]

        tt = str(tt)[2:-2]
        if(100-conf) > 67:
            tt = tt + " [Pass]"
            cv2.putText(im, str(tt), (x+5,y-5), font, 1, (255, 255, 255), 2)
        else:
            cv2.putText(im, str(tt), (x + 5, y - 5), font, 1, (255, 255, 255), 2)

        if (100-conf) > 67:
            cv2.putText(im, str(confstr), (x + 5, y + h - 5), font,1, (0, 255, 0),1 )
        elif (100-conf) > 50:
            cv2.putText(im, str(confstr), (x + 5, y + h - 5), font, 1, (0, 255, 255), 1)
        else:
            cv2.putText(im, str(confstr), (x + 5, y + h - 5), font, 1, (0, 0, 255), 1)



    attendance = attendance.drop_duplicates(subset=['Id'], keep='first')
    cv2.imshow('Attendance', im)
    if (cv2.waitKey(1) == ord('q')):
        break
ts = time.time()
date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
Hour, Minute, Second = timeStamp.split(":")
fileName = "Attendance"+os.sep+"Attendance_"+date+"_"+Hour+"-"+Minute+"-"+Second+".csv"
attendance.to_csv(fileName, index=False)
print("Attendance Successful")
cam.release()
cv2.destroyAllWindows()

每当我尝试编译我的代码时,我都会看到以下错误:

    Traceback (most recent call last):
  
    File "C:\Python\Python39\lib\site-packages\pandas\core\indexes\base.py", line 3080, in get_loc
    return self._engine.get_loc(casted_key)
 
     File "pandas\_libs\index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
 
     File "pandas\_libs\index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc    

      File "pandas\_libs\hashtable_class_helper.pxi", line 4554, in 

    pandas._libs.hashtable.PyObjectHashTable.get_item

      File "pandas\_libs\hashtable_class_helper.pxi", line 4562, in 
    pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: 'Id'


The above exception was the direct cause of the following exception:



Traceback (most recent call last):
  File "I:\image processing\data\fyp\main.py", line 101, in <module>

    mainMenu()

 
 File "I:\image processing\data\fyp\main.py", line 47, in mainMenu
    RecognizeFaces()

  File "I:\image processing\data\fyp\main.py", line 95, in RecognizeFaces
    Recognize.recognize_attendence()

  File "I:\image processing\data\fyp\Recognize.py", line 38, in recognize_attendence
    aa = df.loc[df['Id'] == Id]['Name'].values

  File "C:\Python\Python39\lib\site-packages\pandas\core\frame.py", line 3024, in __getitem__
    indexer = self.columns.get_loc(key)

  File "C:\Python\Python39\lib\site-packages\pandas\core\indexes\base.py", line 3082, in get_loc
    raise KeyError(key) from err

KeyError: 'Id'
>>> 

在我的情况下,我试图引用的 StudentDetails.csv 中缺少 Id 和 Name 列。 所以我手动将它们放入文件中,然后这个错误就消失了。

出现错误时我的 csv 文件的图像

解决错误后我的 csv 文件的图像

暂无
暂无

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

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