目录

简介

一、InsightFace介绍 

二、安装

三、快速体验

四、代码实战

1、人脸检测

 2、人脸识别


简介

目前github有非常多的人脸识别开源项目,下面列出几个常用的开源项目:

1、deepface

2、CompreFace

3、face_recognition

4、insightface

5、facenet

6、facenet-pytorch

开源的人脸检测项目非常多,本文介绍一下insightface的使用方法。首先给出insightface的官方效果图:

resnet50 arcface人脸识别 starface人脸检测_计算机视觉

 再看一下insightface的网图检测效果:

resnet50 arcface人脸识别 starface人脸检测_人脸检测_02

效果展示结束,下面进入详细的介绍。

一、InsightFace介绍 

insightface是一个开源的基于Pytorch和MXNet实现的2D/3D人脸分析工具,它实现了多个SOTA人脸识别、人脸检测、人脸对齐算法,并对训练和部署进行了优化。目前insightface主分支要求PyTorch 1.6+/MXNet=1.6-1.8,python 3.x。

二、安装

insightface安装非常简单,使用如下命令:

pip install insightface

安装onnxruntime用于推理(有gpu就把onnxruntime替换为onnxruntime-gpu):

pip install onnxruntime

三、快速体验

insightface给出了代码体验示例,文件路径为examples/demo_analysis.py,直接运行该文件,可以得到以下结果:

resnet50 arcface人脸识别 starface人脸检测_人工智能_03

 注意:可能遇到以下报错“AttributeError: module 'numpy' has no attribute 'int'.”

AttributeError: module 'numpy' has no attribute 'int'.
`np.int` was a deprecated alias for the builtin `int`. To avoid this error in existing code, use `int` by itself. Doing this will not modify any behavior and is safe. When replacing `np.int`, you may wish to use e.g. `np.int64` or `np.int32` to specify the precision. If you wish to review your current use, check the 
release note link for additional information.

解决方法:找到安装包目录的face_analysis.py文件,比如\xxxx\envs\blog\lib\site-packages\insightface\app\face_analysis.py,将该文件内的所有np.int替换为‘int’(记得带上‘’),如以下代码(该报错可能由于numpy版本问题引起):

def draw_on(self, img, faces):
        import cv2
        dimg = img.copy()
        for i in range(len(faces)):
            face = faces[i]
            box = face.bbox.astype('int')           #      《=====看这里
            color = (0, 0, 255)
            cv2.rectangle(dimg, (box[0], box[1]), (box[2], box[3]), color, 2)
            if face.kps is not None:
                kps = face.kps.astype("int")         #      《=====看这里
                #print(landmark.shape)
                for l in range(kps.shape[0]):
                    color = (0, 0, 255)
                    if l == 0 or l == 3:
                        color = (0, 255, 0)
                    cv2.circle(dimg, (kps[l][0], kps[l][1]), 1, color,
                               2)
            if face.gender is not None and face.age is not None:
                cv2.putText(dimg,'%s,%d'%(face.sex,face.age), (box[0]-1, box[1]-4),cv2.FONT_HERSHEY_COMPLEX,0.7,(0,255,0),1)

            #for key, value in face.items():
            #    if key.startswith('landmark_3d'):
            #        print(key, value.shape)
            #        print(value[0:10,:])
            #        lmk = np.round(value).astype(np.int)
            #        for l in range(lmk.shape[0]):
            #            color = (255, 0, 0)
            #            cv2.circle(dimg, (lmk[l][0], lmk[l][1]), 1, color,
            #                       2)
        return dimg

四、代码实战

examples/demo_analysis.py已经给出了使用示例,下面对部分代码进行解释,并给出测试结果。

1、人脸检测

使用如下代码即可得到人脸检测的结果:

import cv2
import numpy as np
from insightface.app import FaceAnalysis

app = FaceAnalysis(name='buffalo_sc')   # 使用的检测模型名为buffalo_sc
app.prepare(ctx_id=-1, det_size=(640, 640))  # ctx_id小于0表示用cpu预测,det_size表示resize后的图片分辨率  

img = cv2.imread("multi_people.webp")  # 读取图片
faces = app.get(img)   # 得到人脸信息
rimg = app.draw_on(img, faces)   # 将人脸框绘制到图片上
cv2.imwrite("multi_people_output.jpg", rimg)        # 保存图片

结果如下:

resnet50 arcface人脸识别 starface人脸检测_深度学习_04

 2、人脸识别

检测到人脸之后,通常将人脸编码为特征向量,再通过特征向量的相似度对比判断2个人脸是否为一个人,下面给出从图片中识别指定人脸的代码,以上图为例,目标人脸为最左侧的人脸,如下图:

resnet50 arcface人脸识别 starface人脸检测_深度学习_05

 识别的代码如下:

import cv2
import numpy as np
from insightface.app import FaceAnalysis

app = FaceAnalysis(name='buffalo_sc')   # 使用的检测模型名为buffalo_sc
app.prepare(ctx_id=-1, det_size=(640, 640))  # ctx_id小于0表示用cpu预测,det_size表示resize后的图片分辨率  

img = cv2.imread("multi_people.webp")  # 读取图片
faces = app.get(img)   # 得到人脸信息

# 将人脸特征向量转换为矩阵
feats = []
for face in faces:
    feats.append(face.normed_embedding)
feats = np.array(feats, dtype=np.float32)

# 提取目标人脸向量
target = cv2.imread("target.png")
target_faces = app.get(target)   # 得到人脸信息
target_feat = np.array(target_faces[0].normed_embedding, dtype=np.float32)

# 人脸向量相似度对比
sims = np.dot(feats, target_feat)
target_index = int(sims.argmax())

rimg = app.draw_on(img, [faces[target_index]])   # 将人脸框绘制到图片上
cv2.imwrite("multi_people_output_target.jpg", rimg)        # 保存图片

最后的效果如下:

resnet50 arcface人脸识别 starface人脸检测_人脸检测_06