3

I tried executing the following code for facial recognition in python and got the error as mentioned, what could be the possible cause and what is a solution?

code:

import cv2
import numpy as np
from os import listdir
from os.path import isfile, join

data_path ='/Users/aksheenmalhotra/Desktop/facerecogdata/'
onlyfiles = [f for f in listdir(data_path) if isfile(join(data_path,f))]

Training_Data, Labels = [], []

for i, files in enumerate(onlyfiles):
    image_path = data_path + onlyfiles[i]
    images = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
    Training_Data.append(np.asarray(images,dtype=np.uint8))
    Labels.append(i)

Labels = np.asarray(Labels, dtype=np.int32)

model = cv2.face.LBPHFaceRecognizer_create()

model.train(np.asarray(Training_Data), np.asarray(Labels))

print("Model Training Complete!!!!!")

face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

def face_detector(img, size = 0.5):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_classifier.detectMultiScale(gray,1.3,5)

    if faces is():
        return img,[]

    for(x,y,w,h) in faces:
        cv2.rectangle(img, (x,y),(x+w,y+h),(0,255,255),2)
        roi = img[y:y+h, x:x+w]
        roi = cv2.resize(roi, (200,200))

    return img,roi

cap = cv2.VideoCapture(0)
while True:

    ret, frame = cap.read()

    image, face = face_detector(frame)

    try:
        face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)
        result = model.predict(face)

        if result[1] < 500:
            confidence = int(100*(1-(result[1])/300))
            display_string = str(confidence)+'% Confidence it is user'
        cv2.putText(image,display_string,(100,120), cv2.FONT_HERSHEY_COMPLEX,1,(250,120,255),2)


        if confidence > 75:
            cv2.putText(image, "Unlocked", (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2)
            cv2.imshow('Face Cropper', image)

        else:
            cv2.putText(image, "Locked", (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255), 2)
            cv2.imshow('Face Cropper', image)


    except:
        cv2.putText(image, "Face Not Found", (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 0, 0), 2)
        cv2.imshow('Face Cropper', image)
        pass

    if cv2.waitKey(1)==13:
        break


cap.release()
cv2.destroyAllWindows()

I get the following error traceback. Error:

Traceback (most recent call last):
  File "/Users/aksheenmalhotra/Desktop/python files/18-1-2020/facerecogtrial.py", line 14, in <module>
    Training_Data.append(np.asarray(images,dtype=np.uint8))
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numpy/core/_asarray.py", line 85, in asarray
    return array(a, dtype, copy=False, order=order)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
4
  • if you look carefully in the error traceback you can the error is because one of the arguments of asarray method of numpy do not accept NoneType as value. check which argument is getting passed as None on line no 14 ( hint in the stacktrace) Commented Jan 18, 2020 at 6:22
  • the parameter missing is the memory representation, but even if I change that, the error persists. Commented Jan 18, 2020 at 6:36
  • can you check what values are you getting in image_path at each iteration. also, can you try cv2.imshow() to confirm that images are being read Commented Jan 18, 2020 at 6:41
  • cv2 returns None if it can't find the image file. Commented Jan 18, 2020 at 6:42

1 Answer 1

1

I can reproduce the error message with:

In [210]: np.asarray(None, dtype='uint8')                                                        
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-210-ab1b7ff4c0ab> in <module>
----> 1 np.asarray(None, dtype='uint8')

/usr/local/lib/python3.6/dist-packages/numpy/core/_asarray.py in asarray(a, dtype, order)
     83 
     84     """
---> 85     return array(a, dtype, copy=False, order=order)
     86 
     87 

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

Thus, in

images = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
Training_Data.append(np.asarray(images,dtype=np.uint8))

images is, most likely, None. cv2.imread returns None when it can't read the file, most likely because the file path is wrong.

So a robust use of cv2 should be prepared for this, and test for None, and skip or raise an error.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.