Site icon Machine Learning Projects

How to perform Face Recognition using KNN – with source code – interesting project – 2023

Machine Learning Projects

So in today’s blog, we will see that how we can perform Face Recognition using KNN (K-Nearest Neighbors Algorithm) and Haar cascades. Haar cascades are very fast as compared to other ways of detecting faces (like MTCNN) but with an accuracy tradeoff. Its accuracy is a bit less when compared with these big boys like MTCNNs.

We will be seeing 2 scripts in today’s blog:

Before proceeding please read my previous post: THE EASIEST WAY TO PERFORM FACE AND EYE DETECTION IN PYTHON USING HAARCASCADES AND OPENCV

Code for adding a new face…

import cv2
import numpy as np
import os
import pickle

face_data = []
i = 0

cam = cv2.VideoCapture(0)

facec = cv2.CascadeClassifier('data/haarcascade_frontalface_default.xml')

name = input('Enter your name --> ')
ret = True

# Face Recognition using KNN
while(ret):
    ret, frame = cam.read()
    if ret == True:
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        face_coordinates = facec.detectMultiScale(gray, 1.3, 4)

        for (x, y, w, h) in face_coordinates:
            faces = frame[y:y+h, x:x+w, :]
            resized_faces = cv2.resize(faces, (50, 50))

            if i % 10 == 0 and len(face_data) < 10:
                face_data.append(resized_faces)
            cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
        i += 1

        cv2.imshow('frames', frame)

        if cv2.waitKey(1) == 27 or len(face_data) >= 10:
            break
    else:
        print('error')
        break


cv2.destroyAllWindows()
cam.release()


face_data = np.asarray(face_data)
face_data = face_data.reshape(10, -1)

if 'names.pkl' not in os.listdir('data/'):
    names = [name]*10
    with open('data/names.pkl', 'wb') as f:
        pickle.dump(names, f)
else:
    with open('data/names.pkl', 'rb') as f:
        names = pickle.load(f)

    names = names + [name]*10
    with open('data/names.pkl', 'wb') as f:
        pickle.dump(names, f)


if 'faces.pkl' not in os.listdir('data/'):
    with open('data/faces.pkl', 'wb') as w:
        pickle.dump(face_data, w)
else:
    with open('data/faces.pkl', 'rb') as w:
        faces = pickle.load(w)

    faces = np.append(faces, face_data, axis=0)
    with open('data/faces.pkl', 'wb') as w:
        pickle.dump(faces, w)

Linewise explanation…

The rectangle around the detected face.
Sam
Sam
Sam
Sam
Sam
Sam
Sam
Sam
Sam
Sam
Nick
Nick
Structure of names.pkl
Face 1 of sam7500 columns depicting this face
Face 2 of sam7500 columns depicting this face
Face 3 of sam7500 columns depicting this face
Face 4 of sam7500 columns depicting this face
Face 5 of sam7500 columns depicting this face
Face 6 of sam7500 columns depicting this face
Face 7 of sam7500 columns depicting this face
Face 8 of sam7500 columns depicting this face
Face 9 of sam7500 columns depicting this face
Face 10 of sam7500 columns depicting this face
Face 1 of nick7500 columns depicting this face
Face 2 of nick7500 columns depicting this face
Structure of faces.pkl

Code for Live Face Recognition using KNN…

import cv2
import numpy as np
import pickle
from sklearn.neighbors import KNeighborsClassifier

with open('data/faces.pkl', 'rb') as w:
    faces = pickle.load(w)

with open('data/names.pkl', 'rb') as f:
    labels = pickle.load(f)

facec = cv2.CascadeClassifier('data/haarcascade_frontalface_default.xml')

cam = cv2.VideoCapture(0)

print('Shape of Faces matrix --> ', faces.shape)
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(faces,labels)

# Face Recognition using KNN
while True:
    ret, fr = cam.read()
    if ret == True:
        gray = cv2.cvtColor(fr, cv2.COLOR_BGR2GRAY)
        face_coordinates = facec.detectMultiScale(gray, 1.3, 5)

        for (x, y, w, h) in face_coordinates:
            fc = fr[y:y + h, x:x + w, :]
            r = cv2.resize(fc, (50, 50)).flatten().reshape(1,-1)
            text = knn.predict(r)
            cv2.putText(fr, text[0], (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 2)
            cv2.rectangle(fr, (x, y), (x + w, y + w), (0, 0, 255), 2)

        cv2.imshow('livetime face recognition', fr)
        if cv2.waitKey(1) == 27:
            break
    else:
        print("error")
        break

cv2.destroyAllWindows()

Linewise explanation…

The shape of the faces matrix

Results of Face Recognition using KNN…

https://machinelearningprojects.net/wp-content/uploads/2022/07/face-recognition-using-knn.mp4

NOTE This Face Recognition using KNN algorithm and Haarcascades method is fast but not much accurate. In further blogs, we will also discuss better Face Recognition methods.

Download source code for Face Recognition using KNN…

NOTE – The source code that you will download will not be having any face data. Add at least one face to proceed with the code.

Do let me know if there’s any query regarding Face Recognition using KNN by contacting me on email or LinkedIn.

So this is all for this blog folks, thanks for reading it and I hope you are taking something with you after reading this and till the next time ?…

Check out my other machine learning projectsdeep learning projectscomputer vision projectsNLP projectsFlask projects at machinelearningprojects.net.

Exit mobile version