Last active
January 24, 2022 10:27
-
-
Save birddevelper/6d1b08ab9b617f1a40bde9e97a4785f5 to your computer and use it in GitHub Desktop.
FaceNet usage sample code. (How FaceNet Works and How to Work With FaceNet)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tensorflow as tf | |
import glob | |
from mtcnn import MTCNN | |
from tensorflow.keras.models import load_model | |
import cv2 | |
import numpy as np | |
from scipy.spatial.distance import cosine | |
detector = MTCNN() | |
facenet_model = load_model("facenet_keras.h5") | |
encoding_dict = {} | |
def extract_face_and_preprocessing(image): | |
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) | |
faces = detector.detect_faces(image) | |
x1, y1, width, height = faces[0]["box"] | |
x1, y1 = abs(x1), abs(y1) | |
x2, y2 = x1 + width, y1+height | |
face = image[y1:y2, x1:x2] | |
face = cv2.resize(face, (160, 160)) | |
face = np.expand_dims(face, axis = 0) | |
face = (face - face.mean())/face.std() | |
return face, (x1, x2, y1, y2) | |
def get_encode(): | |
for item in glob.glob("faces\\*\\*"): | |
img = cv2.imread(item) | |
face , _= extract_face_and_preprocessing(img) | |
encode = facenet_model.predict(face) | |
encoding_dict[item.split("\\")[-2]] = encode | |
get_encode() | |
name = "Unkown" | |
distance = float("inf") | |
test_image = cv2.imread("test\\6.jpg") | |
face, (x1, x2, y1, y2) = extract_face_and_preprocessing(test_image) | |
encode = facenet_model.predict(face) | |
for db_name, db_encode in encoding_dict.items(): | |
dist = cosine(encode, db_encode) | |
if dist < 0.5 and dist < distance: | |
name = db_name | |
distance = dist | |
if name == "Unkown": | |
cv2.rectangle(test_image, (x1, y1), (x2, y2), (0, 0, 255), 2) | |
cv2.putText(test_image, "Unknown", (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) | |
else: | |
cv2.rectangle(test_image, (x1, y1), (x2, y2), (0, 255, 0), 2) | |
cv2.putText(test_image, "{}:{:.2f}".format(name, distance), (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2) | |
cv2.imshow("image", test_image) | |
cv2.waitKey(0) | |
cv2.destroyAllWindows() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How FaceNet Works and How to Work With FaceNet