Ask Your Question

Revision history [back]

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

This is the error

image description

Here is my code

image description image description image description image description image description image description

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

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

This is the error

image descriptionimage description

Here is my 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"):
        continue;

    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("."):
            continue;

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

        # read image
        image description = cv2.imread(image_path)

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

        # 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
            faces.append(face)
            # add label for this face
            labels.append(label)

cv2.destroyAllWindows()
cv2.waitKey(1)
cv2.destroyAllWindows()

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 description 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 descriptionusing 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 = cv2.imread("C:\Users\darsh\PycharmProjects\helloworld\test-data\test2.jpg")

perform a prediction

predicted_img1 = predict(test_img1) predicted_img2 = predict(test_img2) print("Prediction complete")

display both images

cv2.imshow(subjects[1], cv2.resize(predicted_img1, (400, 500))) cv2.imshow(subjects[2], cv2.resize(predicted_img2, (400, 500))) cv2.waitKey(0) cv2.destroyAllWindows() cv2.waitKey(1) cv2.destroyAllWindows()

click to hide/show revision 4
None

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

berak gravatar image

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

This is the error

image description

Here is the code

import cv2

cv2 import os

os import numpy as np

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

Presley"] # function to detect face using OpenCV

OpenCV def detect_face(img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

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)

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"):
         continue;

     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("."):
             continue;

         # 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)))
         cv2.waitKey(100)

         # 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
             faces.append(face)
             # add label for this face
             labels.append(label)

 cv2.destroyAllWindows()
 cv2.waitKey(1)
 cv2.destroyAllWindows()

 return faces, labels

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

prepared") # print total faces and labels

labels print("Total faces: ", len(faces)) print("Total labels: ", len(labels))

len(labels)) # create our LBPH face recognizer

recognizer face_recognizer = cv2.face.LBPHFaceRecognizer_create()

cv2.face.LBPHFaceRecognizer_create() # train our face recognizer of our training faces

faces face_recognizer.train(faces, np.array(labels))

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)

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

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)

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...")

images...") # load test images

images test_img1 = cv2.imread("C:\Users\darsh\PycharmProjects\helloworld\test-data\test1.jpg") cv2.imread("C:\\Users\\darsh\\PycharmProjects\\helloworld\\test-data\\test1.jpg") test_img2 = cv2.imread("C:\Users\darsh\PycharmProjects\helloworld\test-data\test2.jpg")

cv2.imread("C:\\Users\\darsh\\PycharmProjects\\helloworld\\test-data\\test2.jpg") # perform a prediction

prediction predicted_img1 = predict(test_img1) predicted_img2 = predict(test_img2) print("Prediction complete")

complete") # display both images

images cv2.imshow(subjects[1], cv2.resize(predicted_img1, (400, 500))) cv2.imshow(subjects[2], cv2.resize(predicted_img2, (400, 500))) cv2.waitKey(0) cv2.destroyAllWindows() cv2.waitKey(1) cv2.destroyAllWindows()

cv2.destroyAllWindows()