cv2.face.LBPHFaceRecognizer_create().predict() is showing all users with my name!
I was making a Face Recognition System; I almost succeed but I noticed, my name is showing for Elon Musk! Where it should be shown as Unknown!
Face Recognizer.py:
import json
import cv2
import numpy as np
print("Please press ESC to close!")
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('Trainer/trainer.yml')
cascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath)
font = cv2.FONT_HERSHEY_SIMPLEX
id = 2
with open('index.json', 'r') as f:
db = json.load(f)
names = {}
for i in db:
for face in db['faces']:
names[face] = db['faces'][face]
cam = cv2.VideoCapture(0, cv2.CAP_DSHOW)
cam.set(3, 640)
cam.set(4, 480)
minW = 0.1 * cam.get(3)
minH = 0.1 * cam.get(4)
while True:
ret, img = cam.read()
converted_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
converted_image,
scaleFactor=1.2,
minNeighbors=5,
minSize=(int(minW), int(minH)),
)
for (x, y, w, h) in faces:
id, accuracy = recognizer.predict(converted_image[y:y + h, x:x + w])
if (accuracy < 100):
id = names[str(id)]
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
else:
id = "Unknown"
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
if cv2.imwrite(f"Unknowns/{str(datetime.datetime.now().strftime('%Y-%m-%d-%X')).replace(':', '_')}.jpg", img):
print("Image Saved!")
winsound.Beep(2000, 500)
cv2.putText(img, str(id), (x + 5, y - 5), font, 1, (255, 255, 255), 2)
cv2.imshow('Face Detection', img)
k = cv2.waitKey(10) & 0xff
if k == 27:
break
cam.release()
cv2.destroyAllWindows()
index.json:
{
"faces": {
"1": "Tahsin"
}
}
This is how I'm taking the Samples!
import json
import cv2
import numpy as np
from PIL import Image
import os
cam = cv2.VideoCapture(0,
cv2.CAP_DSHOW)
cam.set(3, 640)
cam.set(4, 480)
detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
face_id = input("Enter a Numeric user ID: ")
face_name = input("Enter a Name: ")
print("Taking samples, look at camera... ")
count = 0
while True:
ret, img = cam.read()
converted_image = cv2.cvtColor(img,
cv2.COLOR_BGR2GRAY)
faces = detector.detectMultiScale(converted_image, 1.3, 5)
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
count += 1
cv2.imwrite("samples/face." + str(face_id) + '.' + str(count) + ".jpg", converted_image[y:y + h, x:x + w])
k = cv2.waitKey(100) & 0xff
if k == 27:
break
elif count >= 50:
break
cv2.imshow('image', img)
with open('index.json', 'r') as f:
db = json.load(f)
if 'faces' in db:
db['faces'][face_id] = face_name
else:
db['faces'] = {}
db['faces'][face_id] = face_name
with open('index.json', 'w') as f:
json.dump(db, f, indent=4)
print("Samples taken!")
cam.release()
cv2.destroyAllWindows()
path = 'samples'
recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
def Images_And_Labels(path):
imagePaths = [os.path.join(path, f) if f.split('.')[1] == face_id else None for f in os.listdir(path)]
faceSamples = []
ids = []
for imagePath in imagePaths:
if imagePath != None:
gray_img = Image.open(imagePath).convert('L')
img_arr = np.array(gray_img, 'uint8')
id = int(os.path.split(imagePath)[-1].split(".")[1])
faces = detector.detectMultiScale(img_arr)
for (x, y, w, h) in faces:
faceSamples.append(img_arr[y:y + h, x:x + w])
ids.append(id)
return faceSamples, ids
print("Training faces. It will take a few seconds. Wait ...")
faces, ids = Images_And_Labels(path)
recognizer.train(faces, np.array(ids))
recognizer.write('trainer/trainer.yml')
print("Model trained, Now we can recognize your face.")