Ask Your Question

I'm trying to run a face recognition program in python using OpenCV but I'm getting the following error which I'm unable to resolve. Any help is greatly appreciated

asked 2019-01-07 08:29:34 -0600

updated 2019-01-07 11:05:27 -0600

berak gravatar image

This is the error

image description

Here is the code

import cv2

import os

import numpy as np

subjects = ["", "Ramiz Raja", "Elvis Presley"]

# function to detect face using OpenCV
def detect_face(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    face_cascade = cv2.CascadeClassifier('C:\\Users\\darsh\\PycharmProjects\\helloworld\\opencv-files\\lbpcascade_frontalface.xml')

    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5);

    # if no faces are detected then return original img
    if (len(faces) == 0):
        return None, None

    # under the assumption that there will be only one face,
    # extract the face area
    (x, y, w, h) = faces[0]

    # return only the face part of the image
    return gray[y:y + w, x:x + h], faces[0]

def prepare_training_data(data_folder_path):
    # ------STEP-1--------
    # get the directories (one directory for each subject) in data folder
    dirs = os.listdir(data_folder_path)

    # list to hold all subject faces
    faces = []
    # list to hold labels for all subjects
    labels = []

    # let's go through each directory and read images within it
    for dir_name in dirs:

        # our subject directories start with letter 's' so
        # ignore any non-relevant directories if any
        if not dir_name.startswith("s"):

        label = int(dir_name.replace("s", ""))

        subject_dir_path = data_folder_path + "\\" + dir_name

        # get the images names that are inside the given subject directory
        subject_images_names = os.listdir(subject_dir_path)

        for image_name in subject_images_names:

            # ignore system files like .DS_Store
            if image_name.startswith("."):

            # build image path
            # sample image path = training-data/s1/1.pgm
            image_path = subject_dir_path + "\\" + image_name

            # read image
            image = cv2.imread(image_path)

            # display an image window to show the image
            cv2.imshow("Training on image...", cv2.resize(image, (400, 500)))

            # detect face
            face, rect = detect_face(image)

            # ------STEP-4--------
            # for the purpose of this tutorial
            # we will ignore faces that are not detected
            if face is not None:
                # add face to list of faces
                # add label for this face


    return faces, labels

print("Preparing data...")
faces, labels = prepare_training_data("C:\\Users\\darsh\\PycharmProjects\\helloworld\\training-data")
print("Data prepared")

# print total faces and labels
print("Total faces: ", len(faces))
print("Total labels: ", len(labels))

# create our LBPH face recognizer
face_recognizer = cv2.face.LBPHFaceRecognizer_create()

# train our face recognizer of our training faces
face_recognizer.train(faces, np.array(labels))

def draw_rectangle(img, rect):
    (x, y, w, h) = rect
    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)

def draw_text(img, text, x, y):
    cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 255, 0), 2)

def predict(test_img):
    # make a copy of the image as we don't want to chang original image
    img = test_img.copy()
    # detect face from the image
    face, rect = detect_face(img)

    # predict the image using our face recognizer
    label, confidence = face_recognizer.predict(face)
    # get name of respective label returned by face recognizer
    label_text = subjects[label[0]]

    # draw a rectangle around face detected
    draw_rectangle(img, rect)
    # draw name of predicted person
    draw_text(img, label_text, rect[0], rect[1] - 5)

    return img

print("Predicting images...")

# load test images
test_img1 = cv2.imread("C:\\Users\\darsh\\PycharmProjects\\helloworld\\test-data\\test1.jpg")
test_img2 ...
edit retag flag offensive close merge delete


please replace all those useless screenshots with a TEXT version, so we can quote you properly, it can be indexed for search, etc. thank you.

berak gravatar imageberak ( 2019-01-07 08:36:58 -0600 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2019-01-07 11:08:01 -0600

berak gravatar image

updated 2019-01-07 11:09:29 -0600

problem is here:

 image = cv2.imread(image_path)

like any other python noob, you NEVER check, if the image was actually loaded, and then you get errors in the NEXT lines ...

please add a check here:

 if image==None:
    print("invalid image ! ", filename)
    return None, None
edit flag offensive delete link more


Thanks a ton!!! The image is not being loaded but kindly guide me about why is this happening? I made sure all the directories contain images accordingly Again thanks a lot.

darsh_priyadharshan gravatar imagedarsh_priyadharshan ( 2019-01-07 11:21:24 -0600 )edit

try to print out the filename of the problematic one, then you can inspect it.

berak gravatar imageberak ( 2019-01-07 11:27:20 -0600 )edit

Question Tools

1 follower


Asked: 2019-01-07 08:29:34 -0600

Seen: 1,468 times

Last updated: Jan 07 '19