I’ve created a model for detecting faces using opencv and other libs.
The problem is that it detetcts all the faces in the group photo as me only and I don’t have any clue how to solve this problem, anyone please help.
Here is the trainer file
import os
import numpy as np
from PIL import Image
import cv2
import pickle
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
recognizer = cv2.face.LBPHFaceRecognizer_create()
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMAGE_DIR = os.path.join(BASE_DIR, "training_images")
current_id = 1
label_ids = {}
y_labels = []
x_train = []
for root, dirs, files in os.walk(IMAGE_DIR):
for file in files:
path = os.path.join(root,file)
label = os.path.basename(root)
# print(path)
# print(label)
if not label in label_ids:
label_ids[label] = current_id
current_id += 1
id_ = label_ids[label]
# print(label_ids)
pil_image = Image.open(path).convert("L") #grayscale
image_array = np.array(pil_image, "uint8")
# print(image_array)
faces = faceCascade.detectMultiScale(image_array, scaleFactor=1.3, minNeighbors=5)
for (x,y,w,h) in faces:
roi = image_array[y:y+x, x:x+w]
x_train.append(roi)
y_labels.append(id_)
with open("labels.pickle", "wb") as f:
pickle.dump(label_ids, f)
recognizer.train(x_train, np.array(y_labels))
recognizer.save("trained-model.yml")
This is the detection file
import cv2
import sys
import numpy as np
import pickle
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("trained-model.yml")
labels = {}
with open("labels.pickle", "rb") as f:
original_labels = pickle.load(f)
labels = {v: k for k, v in original_labels.items()}
def detect(imagePath):
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faceCascade = cv2.CascadeClassifier(
cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
)
faces = faceCascade.detectMultiScale(
gray, scaleFactor=1.3, minNeighbors=3, minSize=(30, 30)
)
print("Found {0} Faces!".format(len(faces)))
for (x, y, w, h) in faces:
roi_gray = gray[y : y + h, x : x + w]
id_, conf = recognizer.predict(roi_gray)
if conf > 9:
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
name = labels[id_]
# Drawing a box around the face
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
# Drawing a label with a name below the face
# cv2.rectangle(image, (x, y + w + 35),(x + w, y + h), (0, 255, 0), cv2.FILLED)
font = cv2.FONT_HERSHEY_DUPLEX
cv2.putText(image, name, (x, y + h + 25), font, 1.0, (0, 0, 255), 1)
status = cv2.imwrite("result_images/faces_detected.jpg", image)
url = ""
if len(faces) > 0:
url = "result_images/faces_detected.jpg"
if url != "":
return {"count": len(faces), "url": url}
else:
return {"count": len(faces), "url": None}
if __name__ == "__main__":
detect("test_images/group.jpg")