ageitgey / face_recognition

The world's simplest facial recognition api for Python and the command line
MIT License
52.99k stars 13.45k forks source link

TypeError: 'NoneType' object is not subscriptable #527

Closed acemi1 closed 6 years ago

acemi1 commented 6 years ago

facerec_from_webcam.py error message

/usr/bin/python3.5 /home/e/Desktop/face_recognition-master/examples/facerec_from_webcam.py Traceback (most recent call last): File "/home/e/Desktop/face_recognition-master/examples/facerec_from_webcam.py", line 37, in rgb_frame = frame[:, :, ::-1] TypeError: 'NoneType' object is not subscriptable

Note1: "rgb_frame = frame [:,:, :: - 1]" is also available on line 46 of the facerec_from_video_file.py file. The facerec_from_video_file.py file is working fine

Note2: pip3 install opencv_python Requirement already satisfied: opencv_python in /usr/local/lib/python3.5/dist-packages (3.4.1.15) Requirement already satisfied: numpy>=1.11.1 in /usr/local/lib/python3.5/dist-packages (from opencv_python) (1.14.4)


facerec_from_webcam_faster.py error message

Traceback (most recent call last): File "/home/e/Desktop/face_recognition-master/examples/facerec_from_webcam_faster.py", line 45, in small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) cv2.error: OpenCV(3.4.1) /io/opencv/modules/imgproc/src/resize.cpp:4044: error: (-215) ssize.width > 0 && ssize.height > 0 in function resize

ageitgey commented 6 years ago

This question comes up all the time, so I added it to the wiki. Check this out: https://github.com/ageitgey/face_recognition/wiki/Common-Errors#issue-assertion-failed-ssizewidth--0--ssizeheight--0-when-running-the-webcam-examples

prasanthkumark commented 6 years ago

Dear Mr. Ageitgey,

People are getting attracted with your articles including me :)

i had downloaded image file available @ Download the pre-configured VM image Installed VMWare Player and added webcam url cv2.VideoCapture("rtsp://admin:admin@10.0.0.8:554/cam/realmonitor?channel=1&subtype=0") Got the video screen while running facerec_from_webcam.py while running i got the error TypeError: 'NoneType' object is not subscriptable, i had gone through your previous post Common-Erros. but no luck

Here is my PC-Configuration

Processor: AMD FX 8120 Eight Core 3.10 GHz Ram: 16GB OS: 64Bit Windows Memory Card: NVidia Quadro 400

saurabhbidwai commented 6 years ago

I'm also facing the same error while using VM

Traceback (most recent call last): File "facerec_from_webcam_my.py", line 37, in rgb_frame = frame[:, :, ::-1] TypeError: 'NoneType' object is not subscriptable

hoggle64 commented 5 years ago

same here:

[mpjpeg @ 0x8fdb880] Expected boundary '--' not found, instead found a line of 3 bytes [mpjpeg @ 0x8fdb880] Expected boundary '--' not found, instead found a line of 6 bytes [mpjpeg @ 0x8fdb880] Expected boundary '--' not found, instead found a line of 5 bytes [mpjpeg @ 0x8fdb880] Expected boundary '--' not found, instead found a line of 5 bytes [mpjpeg @ 0x8fdb880] Expected boundary '--' not found, instead found a line of 47 bytes [mpjpeg @ 0x8fdb880] Expected boundary '--' not found, instead found a line of 19 bytes [mpjpeg @ 0x8fdb880] Expected boundary '--' not found, instead found a line of 22 bytes [mpjpeg @ 0x8fdb880] Expected boundary '--' not found, instead found a line of 8 bytes [mpjpeg @ 0x8fdb880] Expected boundary '--' not found, instead found a line of 8 bytes Traceback (most recent call last): File "./test2.py", line 41, in <module> rgb_frame = frame[:, :, ::-1] TypeError: 'NoneType' object is not subscriptable

abdulqayoomabro commented 4 years ago

rgb_frame = frame[:, :, ::-1] TypeError: 'NoneType' object is not subscriptable any solution????

ravikiranrao commented 4 years ago

Anyone has a solution for this issue?

ghost commented 4 years ago

Does anybody have a solution????!

ageitgey commented 4 years ago

You need to make sure your webcam is working with OpenCV. Your camera isn't returning an image, so you get a NULL image array, causing the error you see. See https://github.com/ageitgey/face_recognition/issues/21#issuecomment-287779524

ghost commented 3 years ago

this worked. rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

Fazaljanan commented 1 year ago

PS C:\Users\DELL\Documents\FaceRecog_attendaceSystem-main.final> & C:/Users/DELL/AppData/Local/Programs/Python/Python311/python.exe c:/Users/DELL/Documents/FaceRecog_attendaceSystem-main.final/Face_Recognition.py Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python311\Lib\tkinter__init.py", line 1948, in call__ return self.func(*args) ^^^^^^^^^^^^^^^^ File "c:\Users\DELL\Documents\FaceRecog_attendaceSystem-main.final\Face_Recognition.py", line 232, in face_recog img = recognize(img, clf, faceCascade) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\DELL\Documents\FaceRecog_attendaceSystem-main.final\Face_Recognition.py", line 220, in recognize coord = draw_boundray(img, faceCascade, 1.1, 10, (255, 255, 255), clf) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\DELL\Documents\FaceRecog_attendaceSystem-main.final\Face_Recognition.py", line 205, in draw_boundray self.mark_attendance(i, r, n,) File "c:\Users\DELL\Documents\FaceRecog_attendaceSystem-main.final\Face_Recognition.py", line 86, in mark_attendance uroll = r[0:5] ~^^^^^ TypeError: 'NoneType' object is not subscriptable PS C:\Users\DELL\Documents\FaceRecog_attendaceSystem-main.final>

Fazaljanan commented 1 year ago
def mark_attendance(self, i, r, n):

if r is None:

#    return
    with open("attendance.csv", "r+", newline="\n") as f:
        myDataList = f.readlines()
        name_list = []
        for line in myDataList:
            entry = line.split((","))
            name_list.append(entry[0])
        if ((i in myDataList) or (r in myDataList) or (n in myDataList) ):
            pass
        elif ((i  in myDataList) and (r not in myDataList) and (n not in myDataList)):
            now = datetime.now()
            d1 = now.strftime("%d/%m/%Y")
            dtString = now.strftime("%H:%M:%S")
            f.writelines(f"\n{i[0]},{r},{n},{dtString},{d1},Present")
           # speak_va("attendance has been added")

        conn = mysql.connector.connect(username='root', password='fazal123', host='localhost', database='face_recognizer1')
        mycursor = conn.cursor()

        if messagebox.askyesno("Confirmation", "Are you sure you want to save attendance on database?"):
            for i in name_list:
                uid = i[0]

                uroll = r[0:5]

                uname = n[0:9]

                udate = datetime.now().strftime("%Y-%m-%d")

                  # Check if time-in exists for the student and date
                check_qry = "SELECT std_timein, std_timeout FROM stdattendance WHERE std_id=%s and std_date=%s"
                mycursor.execute(check_qry, (uid, udate))
                result = mycursor.fetchone()

            if result is None:
                     # Insert time-in for the student and date
                utimein = datetime.now().strftime("%H:%M:%S")
                utimeout = None
                uattend = 'present'
                insert_qry = "INSERT INTO stdattendance(std_id, std_roll_no, std_name, std_date, std_timein, std_timeout, std_attendance) VALUES(%s,%s,%s,%s,%s,%s,%s)"
                mycursor.execute(insert_qry, (uid, uroll, uname, udate, utimein, utimeout, uattend))

            elif result[0] is not None and result[1] is None:
                # Insert time-out for the student and date
                utimeout = datetime.now().strftime("%H:%M:%S")
                update_qry = "UPDATE stdattendance SET std_timeout=%s WHERE std_id=%s and std_date=%s"
                mycursor.execute(update_qry, (utimeout, uid, udate))

            elif result[0] is not None and result[1] is not None:
                       utimeout = datetime.now().strftime("%H:%M:%S")
                       update_qry = "UPDATE stdattendance SET std_timeout=%s WHERE std_roll_no=%s and std_date=%s"
                       mycursor.execute(update_qry, (utimeout, uroll, udate))

                       # Get the latest time-in time
                       check_timein_qry = "SELECT MAX(std_timein) FROM stdattendance WHERE std_id=%s and std_date=%s"
                       mycursor.execute(check_timein_qry, (uroll, udate))
                       latest_timein = mycursor.fetchone()[0]

                        # Update the attendance record with the latest time-in time
                    #   update_qry = "UPDATE stdattendance SET std_timein=%s WHERE std_roll_no=%s and std_date=%s and std_timeout=%s"
                    #   mycursor.execute(update_qry, (latest_timein, uroll, udate, utimeout))    

#            elif result[0] is not None and result[1] is not None and datetime.strptime(result[1], '%H:%M:%S').date() == datetime.now().date():
                        # Update time-out for the student and date
#                utimeout = datetime.now().strftime("%H:%M:%S")
#                update_qry = "UPDATE stdattendance SET std_timeout=%s WHERE std_id=%s and std_date=%s"
#                mycursor.execute(update_qry, (utimeout, uid, udate))

            else:
                    # Insert time-in for the student and date

                utimein = datetime.now().strftime("%H:%M:%S")
                utimeout = None
                uattend = 'present'
                insert_qry = "INSERT INTO stdattendance(std_id, std_roll_no, std_name, std_date, std_timein, std_timeout, std_attendance) VALUES(%s,%s,%s,%s,%s,%s,%s)"
                mycursor.execute(insert_qry, (uid, uroll, uname, udate, utimein, utimeout, uattend))

        # Fetch all results to prevent "

        conn.commit()

        conn.close()

def face_recog(self):
    # rectangle to focus on face
    def draw_boundray(img, classifier, scaleFactor, minNeighbors, color, clf):
        gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        features = classifier.detectMultiScale(gray_image, scaleFactor, minNeighbors)
        coord = []
        for (x, y, w, h) in features:

            cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 3)
            id, predict = clf.predict(gray_image[y:y + h, x:x + w])
            confidence = int((100 * (1 - predict / 300)))

            conn = connect(host="localhost", user="root", password="fazal123", database="face_recognizer1")

            my_cursor = conn.cursor()
            my_cursor.execute("select Name from student where Roll_No="+str(id))
            n = my_cursor.fetchone()

            try:
                n = "+".join(n)
            except Exception as e:
                pass

            my_cursor.execute("select Roll_No from student where Roll_No="+str(id))
            r = my_cursor.fetchone()
            try:
                r = "+".join(r)
            except Exception as e:
                pass

     #       my_cursor.execute("select Department from student where Student_id="+str(id))
     #       d = my_cursor.fetchone()
     #       try:
     #           d = "+".join(d)
     #       except Exception as e:
     #           pass

            my_cursor.execute("select Student_ID from student where Roll_No="+str(id))
            i = my_cursor.fetchone()
            try:
                i = "+".join(i)
            except Exception as e:
                pass
            #recognize face only if confidence is greater than 80%
            if confidence > 80:
                cv2.putText(img, f"Id :{i}", (x, y - 75), cv2.FONT_HERSHEY_COMPLEX, 0.8, (255, 255, 255), 3)
                cv2.putText(img, f"Roll :{r}", (x, y - 55), cv2.FONT_HERSHEY_COMPLEX, 0.8, (255, 255, 255), 3)
                cv2.putText(img, f"Name :{n}", (x, y - 30), cv2.FONT_HERSHEY_COMPLEX, 0.8, (255, 255, 255), 3)
      #          cv2.putText(img, f"Department :{d}", (x, y - 5), cv2.FONT_HERSHEY_COMPLEX, 0.8, (255, 255, 255), 3)
                if id not in lst:
                    lst.append(id)
                    self.mark_attendance(i, r, n,)
                else:
                    break

            else:
                cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 3)

                speak_va("Warning!!! Unknown Face")
                cv2.putText(img, "Unknown Face", (x, y - 5), cv2.FONT_HERSHEY_COMPLEX, 0.8, (255, 255, 255), 3)

            coord = [x, y, w, y]

        return coord

    def recognize(img, clf, faceCascade):
        coord = draw_boundray(img, faceCascade, 1.1, 10, (255, 255, 255), clf)
        if coord is not None:
         return img

    faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
    clf = cv2.face.LBPHFaceRecognizer_create()
    clf.read("classifier.xml")
    video_cap = cv2.VideoCapture(0)
    # increase camera brightness
    video_cap.set(cv2.CAP_PROP_BRIGHTNESS, 0.6)
    while True:
        ret, img = video_cap.read()
        img = recognize(img, clf, faceCascade)

        cv2.imshow("Welcome", img)

        #open camera until enter key is pressed
        if cv2.waitKey(1) == 13: 

            break

    video_cap.release()
    cv2.destroyAllWindows()
    speak_va("thank you")

if name == "main": root = Tk() obj = Face_Recognition(root) root.mainloop()

Fazaljanan commented 1 year ago

fix the error