在异常期间生成KeyError:“ Id”

时间:2019-10-31 09:04:41

标签: python numpy opencv

实际上,我正在尝试跟踪图像,当我单击“跟踪图像”按钮时,它会打开相机,但会提供与ID相关的异常。

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\pc\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 3078, in get_loc
return self._engine.get_loc(key)
File "pandas\_libs\index.pyx", line 140, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 1492, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 1500, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Id'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\pc\Anaconda3\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "I:/Attendence_Project/Attendence.py", line 166, in TrackImages
aa = df.iloc[df['Id'] == Id]['Name'].values
File "C:\Users\pc\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2688, in __getitem__
return self._getitem_column(key)
File "C:\Users\pc\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2695, in _getitem_column
return self._get_item_cache(key)
File "C:\Users\pc\Anaconda3\lib\site-packages\pandas\core\generic.py", line 2489, in _get_item_cache
values = self._data.get(item)
File "C:\Users\pc\Anaconda3\lib\site-packages\pandas\core\internals.py", line 4115, in get
loc = self.items.get_loc(item)
File "C:\Users\pc\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 3080, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas\_libs\index.pyx", line 140, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 1492, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 1500, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Id'

我已将数据保存在CSV(Excel)文件中,并且图像存储在文件夹中。
因为我已经训练了文件夹中存储的图像的数据(YML格式)。
请帮助我消除此错误。

def TrackImages():
    recognizer = cv2.face_LBPHFaceRecognizer.create()
    recognizer.read("TrainingImageLabel\Trainner.yml")
    harcascadePath = "I:\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_default.xml"
    faceCascade = cv2.CascadeClassifier(harcascadePath);
    df = pd.read_csv("StudentDetails\studentDetails.csv",header=0,encoding = 'unicode_escape')
    cam = cv2.VideoCapture(0)
    font = cv2.FONT_HERSHEY_SIMPLEX
    col_names = ['Id','Name','Date','Time']
    attendence = pd.DataFrame(columns = col_names)
    while True:
        ret, im = cam.read()
        gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
        faces = faceCascade.detectMultiScale(gray, 1.2, 5)
        for (x,y,w,h) in faces:
            cv2.rectangle(im, (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.iloc[df['Id'] == Id]['Name'].values      **Error generating line**
                tt = str(Id)+"-"+aa
                attendence.iloc[len(attendence)] = [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)  
        attendence= attendence.drop_duplicates(subset = ['Id'], keep='first')
        cv2.imshow('im',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 = "Attendence\Attendence_" +date+"_"+ Hour+"-"+Minute+"-"+Second+".csv"
    attendence.to_csv(fileName,index=False)
    cam.release()
    cv2.destroyAllWindows()
    res = attendence
    message1.configure(text = res)```

0 个答案:

没有答案