使用facenet进行人脸识别

问题描述 投票:0回答:1

我想用facenet创建一个人脸识别,但我提到的大多数网站都使用tensorflow版本1而不是版本2。我对程序做了一些更改,以便它可以在Tf v2中运行,但图像结果无法识别任何脸。你们知道我的编码有什么问题吗?

import cv2 
import numpy as np
import mtcnn
from architecture import *
from train_v2 import normalize,l2_normalizer
from scipy.spatial.distance import cosine
from tensorflow.keras.models import load_model
import pickle



def get_face(img, box):
    x1, y1, width, height = box
    x1, y1 = abs(x1), abs(y1)
    x2, y2 = x1 + width, y1 + height
    face = img[y1:y2, x1:x2]
    return face, (x1, y1), (x2, y2)

def get_encode(face_encoder, face, size):
    face = normalize(face)
    face = cv2.resize(face, size)
    encode = face_encoder.predict(np.expand_dims(face, axis=0))[0]
    return encode


def load_pickle(path):
    with open(path, 'rb') as f:
        encoding_dict = pickle.load(f)
    return encoding_dict


#required_shape = (160,160)
face_encoder = InceptionResNetV2()
path_m = "facenet_keras_weights.h5"
face_encoder.load_weights(path_m)
people_dir = 'Faces'
encodings_path = 'encodings/encodings.pkl'
test_img_path = 'friends.jpg'
test_res_path = 'result/friends.jpg'


recognition_t = 0.3
required_size = (160, 160)

face_detector = mtcnn.MTCNN()
encoding_dict = load_pickle(encodings_path)



img = cv2.imread(test_img_path)
# plt_show(img)

def detect(img ,detector,encoder,encoding_dict):
    img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    results = detector.detect_faces(img_rgb)
    for res in results:
        face, pt_1, pt_2 = get_face(img_rgb, res['box'])
        encode = get_encode(encoder, face, required_size)
        encode = l2_normalizer.transform(np.expand_dims(encode, axis=0))[0]
        name = 'unknown'

        distance = float("inf")
        for db_name, db_encode in encoding_dict.items():
            dist = cosine(db_encode, encode)
            if dist < recognition_t and dist < distance:
                name = db_name
                distance = dist

        if name == 'unknown':
            cv2.rectangle(img, pt_1, pt_2, (0, 0, 255), 2)
            cv2.putText(img, name, pt_1, cv2.FONT_HERSHEY_PLAIN, 2, (0, 0, 255), 2)
        else:
            cv2.rectangle(img, pt_1, pt_2, (0, 255, 0), 2)
            cv2.putText(img, name + f'__{distance:.2f}', pt_1, cv2.FONT_HERSHEY_PLAIN, 2, (0, 255, 0), 2)

cv2.imwrite(test_res_path, img)
cv2.imshow('Image', img)
cv2.waitKey(0)
tensorflow face-recognition facenet
1个回答
0
投票

为什么不在 python 的 deepface 框架中运行它?

这将验证两个图像是同一个人还是不同的人。

#!pip install deepface
from deepface import DeepFace
res = DeepFace.verify("img1.jpg", "img2.jpg", model_name = 'Facenet')

这将在数据库文件夹中查找 img1.jpg 的标识,并以 pandas 数据帧格式返回候选者。

df = DeepFace.find("img1.jpg", db_path = "C:/database")
print(df.head())

Deepface 构建 Facenet 模型,下载预训练的权重,在后台应用人脸识别管道的预处理阶段(检测和对齐)。你只需要调用它的 verify 或 find 函数即可。

© www.soinside.com 2019 - 2024. All rights reserved.