简体   繁体   English

我不明白我的数组有什么问题

[英]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:\Users\kolya\OneDrive\Рабочий стол\projectGUI\frecognition2.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:\Users\kolya\OneDrive\Рабочий стол\projectGUI\DatabaseGUI.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'\n{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("\n [INFO] Exiting Program and cleanup stuff")
cam.release()
cv2.destroyAllWindows()

The error message "IndexError: list index out of range" means that the length of the array names is inferior to the integer id .错误消息“IndexError: list index out of range”表示数组names的长度低于 integer id

To understand this, just do at line 55:要理解这一点,只需在第 55 行执行:

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

You will see that length <= index .您将看到length <= index

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

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