基于insightface实现的人脸识别和人脸注册

您所在的位置:网站首页 人脸识别专用视频教程 基于insightface实现的人脸识别和人脸注册

基于insightface实现的人脸识别和人脸注册

2024-07-12 05:42| 来源: 网络整理| 查看: 265

本教程的人脸识别是使用的是insightface库进行开发的,该库使用的框架为ONNX,使用的是Anaconda环境。

代码地址:点击下载

安装环境 安装insightface ,安装命令如下。 python -m pip install Cython insightface==0.6.2 -i https://mirror.baidu.com/pypi/simple 安装onnxruntime-gpu,命令如下。 python -m pip install onnxruntime-gpu -i https://mirror.baidu.com/pypi/simple 安装cudatoolkit,命令如下。 conda install cudatoolkit=11.3 cudnn --channel https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/Paddle/ 人脸识别和人脸注册

为了方便,写一个类完成所有的识别流程,开始编写人脸识别和人脸注册工具类,使用insightface.app.FaceAnalysis()可以获取模型对象,这里包含了三个模型,首先是人脸检测模型,然后是人脸特征提取模型,和最后的性别年龄识别模型。使用model.prepare()可以配置ctx_id指定使用哪一块GPU,如果是负数则是使用CPU执行预测,det_thresh配置的是人脸检测的阈值。load_faces()函数是加载人脸库中的人脸,用于之后的人脸识别对比。

import os import cv2 import insightface import numpy as np from sklearn import preprocessing class FaceRecognition: def __init__(self, gpu_id=0, face_db='face_db', threshold=1.24, det_thresh=0.50, det_size=(640, 640)): """ 人脸识别工具类 :param gpu_id: 正数为GPU的ID,负数为使用CPU :param face_db: 人脸库文件夹 :param threshold: 人脸识别阈值 :param det_thresh: 检测阈值 :param det_size: 检测模型图片大小 """ self.gpu_id = gpu_id self.face_db = face_db self.threshold = threshold self.det_thresh = det_thresh self.det_size = det_size # 加载人脸识别模型,当allowed_modules=['detection', 'recognition']时,只单纯检测和识别 self.model = insightface.app.FaceAnalysis(root='./', allowed_modules=None, providers=['CUDAExecutionProvider']) self.model.prepare(ctx_id=self.gpu_id, det_thresh=self.det_thresh, det_size=self.det_size) # 人脸库的人脸特征 self.faces_embedding = list() # 加载人脸库中的人脸 self.load_faces(self.face_db) # 加载人脸库中的人脸 def load_faces(self, face_db_path): if not os.path.exists(face_db_path): os.makedirs(face_db_path) for root, dirs, files in os.walk(face_db_path): for file in files: input_image = cv2.imdecode(np.fromfile(os.path.join(root, file), dtype=np.uint8), 1) user_name = file.split(".")[0] face = self.model.get(input_image)[0] embedding = np.array(face.embedding).reshape((1, -1)) embedding = preprocessing.normalize(embedding) self.faces_embedding.append({ "user_name": user_name, "feature": embedding })

接下来编写recognition()函数实现人脸识别,首先获取每张人脸的特征embedding,其中使用人脸识别的就是通过欧氏距离来对比人脸库中的人脸特征,默认如何它们的欧氏距离小于1.24,我们就可以认为他们是同一个人。

def recognition(self, image): faces = self.model.get(image) results = list() for face in faces: # 开始人脸识别 embedding = np.array(face.embedding).reshape((1, -1)) embedding = preprocessing.normalize(embedding) user_name = "unknown" for com_face in self.faces_embedding: r = self.feature_compare(embedding, com_face["feature"], self.threshold) if r: user_name = com_face["user_name"] results.append(user_name) return results

上面使用到的欧氏距离计算方式如下。

@staticmethod def feature_compare(feature1, feature2, threshold): diff = np.subtract(feature1, feature2) dist = np.sum(np.square(diff), 1) if dist


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3