Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

python - I don't understand what's wrong with my array

Here is my code. When a program sees a face, it must recognize it. My array of names takes data from the database. When I need to recognize I get the following error:

Traceback (most recent call last):
  File "C:UserskolyaOneDriveРабочий столprojectGUIfrecognition2.py", line 56, in <module>
    id = names[id]
IndexError: list index out of range

my code:

import cv2
import numpy as np
import os
import pyodbc
import datetime

#Database
conn = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:UserskolyaOneDriveРабочий столprojectGUIDatabaseGUI.accdb;')
cursor = conn.cursor()
cursor.execute('SELECT User_Name FROM Students')
names = []
names = cursor.fetchall()
#///////////////////

#Logs
def markAttendance(name):
    with open("Attendance.csv", "r+") as f:
        names = f.readlines()
        if name not in names:
            now = datetime.datetime.now()
            f.writelines(f'
{name}, {now}')


recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer/trainer.yml')
cascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);

font = cv2.FONT_HERSHEY_SIMPLEX

id = 0

cam = cv2.VideoCapture(0, cv2.CAP_DSHOW)
cam.set(3, 640) # Ширина
cam.set(4, 480) # Висота

#М?н?мальний розм?р в?кна розп?знавання обличчя
minW = 0.01*cam.get(3)
minH = 0.01*cam.get(4)

while True:
    ret, img = cam.read()
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor = 1.1,
        minNeighbors = 4,
        minSize = (int(minW), int(minH)),
       )

    for(x,y,w,h) in faces:
        cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
        id, confidence = recognizer.predict(gray[y:y+h,x:x+w])
        if (confidence < 80):
            id = names[id]

        else:
            id = "Unkown"

        cv2.putText(img, str(id), (x+5,y-5), font, 1, (255,255,255), 2)

    markAttendance(id)
    cv2.imshow('Camera',img)
    k = cv2.waitKey(10) & 0xff
    if k == 27:
        break

print("
 [INFO] Exiting Program and cleanup stuff")
cam.release()
cv2.destroyAllWindows()
question from:https://stackoverflow.com/questions/65843158/i-dont-understand-whats-wrong-with-my-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The error message "IndexError: list index out of range" means that the length of the array names is inferior to the integer id.

To understand this, just do at line 55:

print("index: ", id, "- length: ", len(names))

You will see that length <= index.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...