--Face recognition with Haar like features (haarcascade_frontalface_default) --Resize + Grace case to reduce dimensions --Learn individual faces with LBPH
!/usr/bin/python
-*- coding: utf-8 -*-
import cv2, os
import numpy as np
from PIL import Image
# Learning image
train_path = './training_data'
# Test image
test_path = './test_data'
# Haar-like feature classifier
cascadePath = "./haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath)
LBPH
recognizer = cv2.createLBPHFaceRecognizer()
def get_images_and_labels(path):
#Array to store images
images = []
# Array to store labels
labels = []
#Array to store filenames
files = []
for f in os.listdir(path):
#Image path
image_path = os.path.join(path, f)
# Import images in grayscale
image_pil = Image.open(image_path).convert('L')
Stored in an array of # NumPy
image = np.array(image_pil, 'uint8')
# Haar-like Feature classifier detects face (parameters are appropriate)
faces = faceCascade.detectMultiScale(image,1.1,9,0)
# Processing of detected face image
for (x, y, w, h) in faces:
# Resize face to 200x200 size
roi = cv2.resize(image[y: y + h, x: x + w], (200, 200), interpolation=cv2.INTER_LINEAR)
#Store images in an array
images.append(roi)
#Get the label from the file name "Assuming a file name like 0_xxxxx.jpg "
labels.append(int(f[0]))
#Store file names in an array
files.append(f)
return images, labels, files
# Get training image
images, labels, files = get_images_and_labels(train_path)
# Training implementation
recognizer.train(images, np.array(labels))
# Get test image
test_images, test_labels, test_files = get_images_and_labels(test_path)
i = 0
while i < len(test_labels):
#Prediction for test images
label, confidence = recognizer.predict(test_images[i])
# Prediction results output to console
print("Test Image: {}, Predicted Label: {}, Confidence: {}".format(test_files[i], label, confidence))
#Display test image
cv2.imshow("test image", test_images[i])
cv2.waitKey(1000)
i += 1
cv2.destroyAllWindows()
Recommended Posts