智客公社

标题: 146.人工智能——基于InsightFace(ONNX模型)人脸识别 [打印本页]

作者: 小姐姐zhousi    时间: 2022-9-21 08:18
标题: 146.人工智能——基于InsightFace(ONNX模型)人脸识别
在前一章中,讲过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 fdimport cv2import numpy as npimport 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 normalizemodel.l2_normalize = True# 预测图片检测结果result0 = model.predict(face0)result1 = model.predict(face1)result2 = model.predict(face2)# 计算余弦相似度#人脸识别模型最终提取的特征embedding,可以用来计算人脸之间的特征相似度embedding0 = result0.embeddingembedding1 = result1.embeddingembedding2 = result2.embeddingcosine01 = cosine_similarity(embedding0, embedding1)cosine02 = cosine_similarity(embedding0, embedding2)# 比对结果,可以设定一个阈值:0.6print("Cosine 01: ", cosine01)print("Cosine 02: ", cosine02)
[attach]788242[/attach]

原图1

[attach]788243[/attach]

原图2

[attach]788244[/attach]

原图3

[attach]788245[/attach]

获取到的人脸,并调整输入图像大小为112*112
#输出结果:余弦相似度比较Cosine 01:  0.8792329727846468  #face0与face1 比较  大于0.6,是同一人Cosine 02:  0.3351910102289668 #face0与face2 比较   小于0.6 不是同一人说明:模型预测前,对获取到的人脸图像大小做了112*112处理。这个直接影响到后面的特征向量的结果。这一点和face_recognition相比,做得不够。
关于FastDeploy根据视觉模型的任务类型,定义了不同的结构体。访问结构体的方式:
结构体变量.成员变量.
如人脸识别:fastdeploy.vision.FaceRecognitionResult
获取result0的embedding的方式:embedding0 = result0.embedding
作者: 潮豫    时间: 2022-9-21 08:19
转发了
作者: AuToPros    时间: 2022-9-21 08:20
转发了




欢迎光临 智客公社 (http://bbs.cnaiplus.com/) Powered by Discuz! X3.4