1、安装环境:

pip install mxnet,python-opencv,tqdm

2、对齐矫正人脸并裁剪

3、用insightface计算相似度,无需安装insightface等,两个脚本即可:

'''
face_analysis.py
'''from __future__ import division
import mxnet as mx
import numpy as np
import os, cv2
import glob
import zipfile
import hashlib
import requests
from tqdm import tqdmclass FaceRecognition:def __init__(self, name, download, param_file):self.name = nameself.download = downloadself.param_file = param_fileself.image_size = (112, 112)if download:assert param_filedef prepare(self, ctx_id, batch_size=1):if self.param_file:pos = self.param_file.rfind('-')prefix = self.param_file[0:pos]pos2 = self.param_file.rfind('.')epoch = int(self.param_file[pos+1:pos2])sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch)all_layers = sym.get_internals()sym = all_layers['fc1_output']if ctx_id>=0:ctx = mx.gpu(ctx_id)else:ctx = mx.cpu()model = mx.mod.Module(symbol=sym, context=ctx, label_names = None)data_shape = (batch_size,3)+self.image_sizemodel.bind(data_shapes=[('data', data_shape)])model.set_params(arg_params, aux_params)#warmupdata = mx.nd.zeros(shape=data_shape)db = mx.io.DataBatch(data=(data,))model.forward(db, is_train=False)embedding = model.get_outputs()[0].asnumpy()self.model = modelelse:passdef get_embedding(self, data):data = mx.nd.array(data)db = mx.io.DataBatch(data=(data,))self.model.forward(db, is_train=False)embedding = self.model.get_outputs()[0].asnumpy()return embeddingdef compute_sim(self, img1, img2):emb1 = self.get_embedding(img1).flatten()emb2 = self.get_embedding(img2).flatten()from numpy.linalg import normsim = np.dot(emb1, emb2)/(norm(emb1)*norm(emb2))return simdef get_arcface(name, download=True,root='insightface/models', **kwargs):if not download:return FaceRecognition(name, False, None)else:_file = get_model_file("arcface_%s"%name, root=root)return FaceRecognition(name, True, _file)def arcface_r100_v1(**kwargs):return get_arcface("r100_v1", download=True, **kwargs)def check_sha1(filename, sha1_hash):"""Check whether the sha1 hash of the file content matches the expected hash.Parameters----------filename : strPath to the file.sha1_hash : strExpected sha1 hash in hexadecimal digits.Returns-------boolWhether the file content matches the expected hash."""sha1 = hashlib.sha1()with open(filename, 'rb') as f:while True:data = f.read(1048576)if not data:breaksha1.update(data)sha1_file = sha1.hexdigest()l = min(len(sha1_file), len(sha1_hash))return sha1.hexdigest()[0:l] == sha1_hash[0:l]def download(url, path=None, overwrite=False, sha1_hash=None):"""Download an given URLParameters----------url : strURL to downloadpath : str, optionalDestination path to store downloaded file. By default stores to thecurrent directory with same name as in url.overwrite : bool, optionalWhether to overwrite destination file if already exists.sha1_hash : str, optionalExpected sha1 hash in hexadecimal digits. Will ignore existing file when hash is specifiedbut doesn't match.Returns-------strThe file path of the downloaded file."""if path is None:fname = url.split('/')[-1]else:path = os.path.expanduser(path)if os.path.isdir(path):fname = os.path.join(path, url.split('/')[-1])else:fname = pathif overwrite or not os.path.exists(fname) or (sha1_hash and not check_sha1(fname, sha1_hash)):dirname = os.path.dirname(os.path.abspath(os.path.expanduser(fname)))if not os.path.exists(dirname):os.makedirs(dirname)print('Downloading %s from %s...'%(fname, url))r = requests.get(url, stream=True)if r.status_code != 200:raise RuntimeError("Failed downloading url %s"%url)total_length = r.headers.get('content-length')with open(fname, 'wb') as f:if total_length is None: # no content length headerfor chunk in r.iter_content(chunk_size=1024):if chunk: # filter out keep-alive new chunksf.write(chunk)else:total_length = int(total_length)for chunk in tqdm(r.iter_content(chunk_size=1024),total=int(total_length / 1024. + 0.5),unit='KB', unit_scale=False, dynamic_ncols=True):f.write(chunk)if sha1_hash and not check_sha1(fname, sha1_hash):raise UserWarning('File {} is downloaded but the content hash does not match. ' \'The repo may be outdated or download may be incomplete. ' \'If the "repo_url" is overridden, consider switching to ' \'the default repo.'.format(fname))return fnamedef find_params_file(dir_path):if not os.path.exists(dir_path):return Nonepaths = glob.glob("%s/*.params"%dir_path)if len(paths)==0:return Nonepaths = sorted(paths)return paths[-1]def get_model_file(name, root=os.path.join('insightface', 'models')):r"""Return location for the pretrained on local file system.This function will download from online model zoo when model cannot be found or has mismatch.The root directory will be created if it doesn't exist.Parameters----------name : strName of the model.root : str, default '~/.mxnet/models'Location for keeping the model parameters.Returns-------file_pathPath to the requested pretrained model file."""_model_sha1 = {name: checksum for checksum, name in [('95be21b58e29e9c1237f229dae534bd854009ce0', 'arcface_r100_v1'),('', 'arcface_mfn_v1'),('39fd1e087a2a2ed70a154ac01fecaa86c315d01b', 'retinaface_r50_v1'),('2c9de8116d1f448fd1d4661f90308faae34c990a', 'retinaface_mnet025_v1'),('0db1d07921d005e6c9a5b38e059452fc5645e5a4', 'retinaface_mnet025_v2'),('7dd8111652b7aac2490c5dcddeb268e53ac643e6', 'genderage_v1'),]}base_repo_url = 'http://insightface.ai/files/'_url_format = '{repo_url}models/{file_name}.zip'file_name = nameroot = os.path.expanduser(root)dir_path = os.path.join(root, name)file_path = find_params_file(dir_path)#file_path = os.path.join(root, file_name + '.params')sha1_hash = _model_sha1[name]if file_path is not None:if check_sha1(file_path, sha1_hash):return file_pathelse:print('Mismatch in the content of model file detected. Downloading again.')else:print('Model file is not found. Downloading.')if not os.path.exists(root):os.makedirs(root)if not os.path.exists(dir_path):os.makedirs(dir_path)zip_file_path = os.path.join(root, file_name + '.zip')repo_url = base_repo_urlif repo_url[-1] != '/':repo_url = repo_url + '/'download(_url_format.format(repo_url=repo_url, file_name=file_name),path=zip_file_path,overwrite=True)with zipfile.ZipFile(zip_file_path) as zf:zf.extractall(dir_path)os.remove(zip_file_path)file_path = find_params_file(dir_path)if check_sha1(file_path, sha1_hash):return file_pathelse:raise ValueError('Downloaded file has different hash. Please try again.')

调用face_analysis.py即可多张图片同时inference求相似度,也可以将结果放到pytorch中调用:

from face_analysis import *
import cv2
import numpy as np
import torchclass FaceAnalysis:def __init__(self, ctx_id=-1, batch_size=1, rec_name='arcface_r100_v1'):if rec_name is not None:self.rec_model = arcface_r100_v1()else:self.rec_model = Noneif self.rec_model is not None:self.rec_model.prepare(ctx_id=ctx_id, batch_size=batch_size)def get(self, data):# if self.rec_model is not None:#     self.rec_model.prepare(ctx_id, batch_size=1)embedding = Noneif self.rec_model is not None:embedding = self.rec_model.get_embedding(data)return embeddinginsface_model = FaceAnalysis(ctx_id=-1)#cpu:-1,gpu:1img = cv2.imread('face.png')img = cv2.resize(img[19:237, 19:237], (112, 112))
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
data = np.transpose(img, (2,0,1))
data = np.expand_dims(data, axis=0)img2 = cv2.imread('girl.png')
img2 = cv2.resize(img2[19:237, 19:237], (112, 112))
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)
data2 = np.transpose(img2, (2,0,1))
data2 = np.expand_dims(data2, axis=0)a= []
a.append(data)
a.append(data2)
datas = np.vstack(a)
batch_size = 2
emb = insface_model.get(datas)
print(emb.shape)
emb1 = emb[0].flatten()
emb2 = emb[1].flatten()
from numpy.linalg import norm
sim = np.dot(emb1, emb2)/(norm(emb1)*norm(emb2))
print(sim)
# embedding_norm = norm(embedding)
# normed_embedding = embedding / embedding_norm
emb = =torch.from_numpy(emb)

如何利用insightface同时计算多个人脸相似度相关推荐

  1. CV之FR之MTCNN:基于TF框架利用MTCNN算法检测并对齐人脸图像进(人脸识别/人脸相似度)而得出人脸特征向量从而计算两张人脸图片距离案例应用之详细攻略

    CV之FR之MTCNN:基于TF框架利用MTCNN算法检测并对齐人脸图像进(人脸识别/人脸相似度)而得出人脸特征向量从而计算两张人脸图片距离案例应用之详细攻略 目录 基于TF框架利用MTCNN算法检测 ...

  2. python 摄像头标定_python 3利用Dlib 19.7实现摄像头人脸检测特征点标定

    Python 3 利用 Dlib 19.7 实现摄像头人脸检测特征点标定 0.引言 利用python开发,借助Dlib库捕获摄像头中的人脸,进行实时特征点标定: 图1 工程效果示例(gif) 图2 工 ...

  3. 利用openssl来计算sha1, sha224, sha256, sha384, sha512

    转载:http://blog.csdn.net/stpeace/article/details/42371079 利用openssl来计算sha1, sha224, sha256, sha384, s ...

  4. 利用scipy包计算表格线的峰值,还原表格得到表格结构

    1. 利用scipy包计算表格线的峰值 import cv2 import numpy as np from scipy.signal import find_peaks, peak_widthsde ...

  5. 利用MSFM算法计算程函方程的走时CT胖射线反演法

    利用MSFM算法计算程函方程的走时CT胖射线反演法 基于程函方程的弹性波走时CT胖射线反演方法,是在反演迭代过程中,利用程函方程计算走时场,并得到接收点处的走时数据,用这个数据代替正演数据.每次迭代完 ...

  6. 我的第一个MPI程序:利用矩形规则计算pi

    利用矩形规则计算pi #include<mpi.h> #include<iostream> using namespace std;   const int INTERVALS ...

  7. 怎么利用计算机公式计算完成比例,excel表格数据计算所占比例公式的使用教程...

    Excel中经常需要使用到公式计算所占比例,所占比例具体该如何利用函数进行计算呢?接下来是学习啦小编为大家带来的excel表格数据计算所占比例公式的使用教程,供大家参考. excel表格数据计算所占比 ...

  8. python计算圆周率近似值_怎样利用python来计算出圆周率π-百度经验

    怎样利用python来计算出圆周率π? 方法/步骤 1 圆周率π是一个无理数,没有任何一个精确公式可以计算出π值,π的计算只能采用近似算法. 我们利用蒙特卡洛方法来求得π的近似值. 蒙特卡洛方法是利用 ...

  9. 【JavaBigDecimal练习】利用BigDecimal精确计算欧拉数

    利用BigDecimal精确计算欧拉数小数点后面1000位 相信大家对于泰勒展开已经稔熟于心,接下来我们就利用下列的泰勒展开: e x = 1 + 1 1 ! x + 1 2 ! x 2 + 1 3 ...

  10. 计算机函数if80到90分怎么弄,用EXCEL工作表怎样利用IF函数计算分数等级

    用EXCEL工作表怎样利用IF函数计算分数等级 01 打开保存有分数的表格,如图所示.这里假设分数设为 A:90分以上(含90) B:80~89 C:70~79 D:60~69 E:60以下(不含60 ...

最新文章

  1. hdu 3064
  2. 两个半月!出差终于结束啦
  3. 详细解读CSS链接属性——Web前端系列学习笔记
  4. SpringAOP的Aspectj方式*
  5. 荣耀6plus+android5.1,荣耀66Plus EMUI3.0开发版5.5.1版本发布说明
  6. SQL Server 2005/2008 导入导出数据常见报错
  7. 50 jQuery绑定事件 阻止默认事件发生 内置动画 each data
  8. js进阶 11-15 jquery过滤方法有哪些
  9. 每日学习小记 11/02
  10. 鸿蒙荣耀9X公测,荣耀9X系列手机开启EMUI 10公测更新
  11. 绕过模拟器检测_用模拟器玩刺激战场体验差?这样设置轻松吃鸡
  12. 分式求二阶导数_一道与三角零点距离有关的导数问题
  13. 使用pn532将全加密卡复制到手环上 NFC校园门禁卡模拟教程
  14. 四级词汇——不择手段记单词new
  15. mysql count 1_MySQL中count(1)和count(*)的区别是什么?
  16. libgdx 打飞机游戏实现教程
  17. 每日算法(四十三)-java为了更改的规划城市,需要统计楼栋数目信息。
  18. 如何将RTOS系统启动时间做到“毫秒级”?AliOS Things是这样做的
  19. 深度总结 | 知识蒸馏在推荐系统中的应用
  20. rdma-cq的创建与销毁

热门文章

  1. 单片机c语言程序编写歌谱,单片机简谱程序
  2. kepware怎么读modbus/tcp数据_第479期丨看看这国企9000+的面试题目;国产PLC工控板质量怎么样?...
  3. 2020 数据中心机房建设方案
  4. 有关MongoVUE工具的简单使用---查询和导出
  5. 应急响应.windows
  6. Xshell5(远程终端工具)工具的安装使用 【免费】
  7. android交叉编译libxml2,libxml2 ARM 交叉编译
  8. Javashop-B2B2C多店铺系统,Javashop B2C开源电商系统下载
  9. 企业信息化管理软件,如何走出开发困境
  10. Camtasia怎么添加文字效果