计算机系统应用教程网站

网站首页 > 技术文章 正文

146.人工智能——基于InsightFace(ONNX模型)人脸识别

btikc 2025-01-09 10:47:12 技术文章 28 ℃ 0 评论

在前一章中,讲过RetinaFace的人脸检测,详情参看:145.人工智能——RetinaFace(ONNX模型)的人脸检测

本文主要体验一下InsightFace(ONNX模型)人脸识别。CosFace-r34模型,下载地址:https://bj.bcebos.com/paddlehub/fastdeploy/glint360k_cosface_r34.onnx。

模型

大小

精度 (AgeDB_30)

CosFace-r34

131MB

98.3

在前期的文章中,有讲过基于face_recognition人脸检测与比对,详情可以参看:9.实时证照相片与人脸验证比对。效果还是非常不错,是返回人脸128个特征向量,通过计算欧氏距离来判断人脸的相似度。缺点就是安装dlib库比较麻烦。

而本文InsightFace的人脸比对是通过余弦相似度来判断。整个过程:

先检测人脸,对人脸图像大小预处理,再进行预测,根据预测的结果,提取人脸特征向量,再根据特征向量进行余弦相似度比对。

实现代码

import fastdeploy as fd
import cv2
import numpy as np
import facedet #人脸检测
# 余弦相似度
def cosine_similarity(a, b):
    a = np.array(a)
    b = np.array(b)
    mul_a = np.linalg.norm(a, ord=2)
    mul_b = np.linalg.norm(b, ord=2)
    mul_ab = np.dot(a, b)
    return mul_ab / (np.sqrt(mul_a) * np.sqrt(mul_b))

#处理人脸数据大小112*112,影响预测结果
def ResizeByLong(img,size=112):
    img0=(np.ones((size,size,3))*255).astype(np.uint8)
    h0,w0=img.shape[:2]
    if h0>w0:
        h=size
        w=w0/h0*size
        img=cv2.resize(img,[int(w),int(h)])       
        img0[0:h,(size-int(w))//2:int(w)+(size-int(w))//2]=img[:,:]
    else:
        w=size
        h=h0/w0*size
        img=cv2.resize(img,[int(w),int(h)])
        img0[(size-int(h))//2:int(h)+(size-int(h))//2,0:int(w)]=img[:,:]
    return img0
        
model_file="faceidmodel/glint360k_cosface_r34.onnx"

#加载模型
model = fd.vision.faceid.CosFace(model_file, runtime_option=None)

#检测人脸,返回人脸图像
face0=ResizeByLong(facedet.getface("img/000.jpg")) #0和1同一人
face1=ResizeByLong(facedet.getface("img/001.jpg"))
face2=ResizeByLong(facedet.getface("img/002.jpg")) #0和2不同一人                     

face=np.hstack((face0,face1,face2))
cv2.imshow("face",face)
cv2.waitKey(0)
cv2.destroyAllWindows()

# 设置 l2 normalize
model.l2_normalize = True

# 预测图片检测结果
result0 = model.predict(face0)
result1 = model.predict(face1)
result2 = model.predict(face2)

# 计算余弦相似度
#人脸识别模型最终提取的特征embedding,可以用来计算人脸之间的特征相似度
embedding0 = result0.embedding
embedding1 = result1.embedding
embedding2 = result2.embedding

cosine01 = cosine_similarity(embedding0, embedding1)
cosine02 = cosine_similarity(embedding0, embedding2)

# 比对结果,可以设定一个阈值:0.6
print("Cosine 01: ", cosine01)
print("Cosine 02: ", cosine02)
#输出结果:余弦相似度比较
Cosine 01:  0.8792329727846468  #face0与face1 比较  大于0.6,是同一人
Cosine 02:  0.3351910102289668 #face0与face2 比较   小于0.6 不是同一人

说明:模型预测前,对获取到的人脸图像大小做了112*112处理。这个直接影响到后面的特征向量的结果。这一点和face_recognition相比,做得不够。


关于FastDeploy根据视觉模型的任务类型,定义了不同的结构体。访问结构体的方式:

结构体变量.成员变量.

如人脸识别:fastdeploy.vision.FaceRecognitionResult

  • embedding(list of float): 成员变量,表示人脸识别模型最终提取的特征embedding,可以用来计算人脸之间的特征相似度。

获取result0的embedding的方式:embedding0 = result0.embedding

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表