Face Detection and Recognition with face_recognition

Source: Deep Learning on Medium

Face Detection and Recognition with face_recognition

This tutorial is about detecting and recognition faces using the face_recognition library. It does not require any model to train.

This tutorial is based on the python programming language. In this tutorial, we will collect the require data-set. We are collecting data-set and save in the folder.

STEP 1: Collect The Data-sets

count = 0
path = userName+count+".jpg"
cap = cv2.VideoCapture(0)
while True:
ret, Image = cap.read()
cv2.imwrite(path,Image)
count+=1
if count > 20:
break
cap.release()
cv2.destroyAllWindows()

STEP 2: Encoding Face

STEP 2: Encoding Face from imutils import paths
import face_recognition
import pickle
import cv2
import os
dataset = "Your Data-set Path"
encodings = "userNameFace.pickle" #name of face encoded data file
imagePaths = list(paths.list_images(dataset))
EncodingValue = []
NamesValue = []
for (i, imagePath) in enumerate(imagePaths):
print("processing image")
name = imagePath.split(os.path.sep)[-2]
image = cv2.imread(imagePath)
image = cv2.resize(image, (100, 100))
rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
boxes = face_recognition.face_locations(rgb, model="cnn")
encodings = face_recognition.face_encodings(rgb, boxes)
for encoding in encodings:
EncodingValue.append(encoding)
NamesValue.append(name)
print("Encoded Data Information")
data = {"Face Rectangle": EncodingValue, "UserName": NamesValue}
f = open("userNameFace.pickle", "wb")
f.write(pickle.dumps(data))
f.close()

STEP 3: Decoding Face

#Require Library
import face_recognition
import pickle
import cv2
#load pickle file
encodings = "userNameFace.pickle"
image = "image.jpeg"
print("Load Pickle File")
data = pickle.loads(open(encodings, "rb").read())
#load image file
image = cv2.imread(image)
rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
#start recognition face
print("Start Recognition Face")
boxes = face_recognition.face_locations(rgb, model="cnn")
encodings = face_recognition.face_encodings(rgb, boxes)

username = []
#start encoding face
for encoding in encodings:
matches = face_recognition.compare_faces(data["encodings"], encoding)
name = ""
if True in matches:
userId = [i for (i, b) in enumerate(matches) if b]
counts = {}
for i in userId:
name = data["UserName"][i]
counts[name] = counts.get(name, 0) + 1
name = max(counts, key=counts.get)
username.append(name)
for ((top, right, bottom, left), name) in zip(boxes, username):
cv2.rectangle(image, (left, top), (right, bottom), (0, 255, 0), 2)
y = top - 15 if top - 15 > 15 else top + 15
cv2.putText(image, name, (left, y), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2)
cv2.imshow("Image", image)
cv2.waitKey(0)

References and Credit

YouTube Demo:

Follow Me