深度学习实践-使用faceNet 进行人脸识别
1.下载facenet模型
facenet需要经过大量的运算,所以直接使用别人训练过的权重
链接:https://pan.baidu.com/s/1CGyz...
提取码:pew0
2. 使用的工具
1. facenet 预训练模型,用于获取人脸特征
2. mtcnn 用于人脸检测并返回对应参数
3. 代码实现
1. 加载模型
from keras.models import load_model
from mtcnn import MTCNN
# 加载mtcnn
dector = MTCNN()
# 加载facenet模型
model = load_model('facenet_keras.h5')
2.根据图片检测人脸
def extract_face(detector, file_name, required_size=(160, 160)):
# detector:mtcnn 对象,file_name:图片路径
# 加载图片
image = Image.open(file_name)
# 将图片转换彩色
image = image.convert('RGB')
# 将图片转换为 array
pixels = asarray(image)
# 使用 mtcnn 检测人脸
results = detector.detect_faces(pixels)
# 返回人脸位置信息
x1, y1, width, height = results[0]['box']
x1, y1 = abs(x1), abs(y1)
x2, y2 = x1 + width, y1 + height
# 从图片剪裁人脸
face = pixels[y1:y2, x1:x2]
# 将剪裁的人脸矩阵化
image = Image.fromarray(face)
# 调整检测人脸图片大小
image = image.resize(required_size)
# 调整矩阵形状
face_array = asarray(image).reshape(1, 160, 160, 3)
return face_array
3.使用facenet 提取人脸特征
def pre_process(x):
if x.ndim == 4:
axis = (1, 2, 3)
size = x[0].size
elif x.ndim == 3:
axis = (0, 1, 2)
size = x.size
else:
raise ValueError('Dimension should be 3 or 4')
mean = np.mean(x, axis=axis, keepdims=True)
std = np.std(x, axis=axis, keepdims=True)
std_adj = np.maximum(std, 1.0 / np.sqrt(size))
y = (x - mean) / std_adj
return y
def get_embedding(model, img):
face_img = pre_process(img)
pre = model.predict(face_img)
pre = l2_normalize(np.concatenate(pre))
pre = np.reshape(pre, [128])
return pre
4.人脸特征对比
当从输入的两张图片中获取到人脸特征后,需要将两张图片的特征进行对比,详细可以参考吴恩达老师的深度学习视频
def face_distance(face_encodings, face_to_compare):
if len(face_encodings) == 0:
return np.empty((0))
return np.linalg.norm(face_encodings - face_to_compare, axis=1)
4.完整代码
import os
from keras.models import load_model
from numpy import expand_dims
import numpy as np
from face_detector import extract_face
from datetime import datetime
from mtcnn import MTCNN
import utils
from PIL import Image
from numpy import asarray
def pre_process(x):
if x.ndim == 4:
axis = (1, 2, 3)
size = x[0].size
elif x.ndim == 3:
axis = (0, 1, 2)
size = x.size
else:
raise ValueError('Dimension 3 or 4')
mean = np.mean(x, axis=axis, keepdims=True)
std = np.std(x, axis=axis, keepdims=True)
std_adj = np.maximum(std, 1.0 / np.sqrt(size))
y = (x - mean) / std_adj
return y
def l2_normalize(x, axis=-1, epsilon=1e-10):
output = x / np.sqrt(np.maximum(np.sum(np.square(x), axis=axis, keepdims=True), epsilon))
return output
def get_embedding(model, img):
face_img = pre_process(img)
pre = model.predict(face_img)
pre = l2_normalize(np.concatenate(pre))
pre = np.reshape(pre, [128])
return pre
def extract_face(detector, file_name, required_size=(160, 160)):
# 加载图片
image = Image.open(file_name)
# 将图片转换彩色
image = image.convert('RGB')
# 将图片转换为 array
pixels = asarray(image)
# 使用 mtcnn 检测人脸
results = detector.detect_faces(pixels)
# 返回人脸位置信息
x1, y1, width, height = results[0]['box']
x1, y1 = abs(x1), abs(y1)
x2, y2 = x1 + width, y1 + height
# 从图片剪裁人脸
face = pixels[y1:y2, x1:x2]
# 将剪裁的人脸矩阵化
image = Image.fromarray(face)
# 调整检测人脸图片大小
image = image.resize(required_size)
# 调整矩阵形状
face_array = asarray(image).reshape(1, 160, 160, 3)
return face_array
def face_distance(face_encodings, face_to_compare):
if len(face_encodings) == 0:
return np.empty((0))
return np.linalg.norm(face_encodings - face_to_compare, axis=1)
def verify_demo():
model = load_model('facenet_keras.h5')
dector = MTCNN()
org_list = []
# 图片路径,修改成自己的图片路径
image1_path = 'images\camera_0.jpg'
pixels = extract_face(dector, image1_path)
embedding1 = get_embedding(model, pixels)
org_list.append(embedding1)
# 图片路径,修改成自己的图片路径
image2_path = 'vertify\younes.jpg'
pixels1 = extract_face(dector, image2_path)
embedding2 = get_embedding(model, pixels1)
dist = face_distance(org_list, embedding2)
print(dist)
if dist < 0.6:
print("欢迎 " + str('ounes') + "回家!")
else:
print("经验证,您与" + str('ounes') + "不符!")
if __name__ == '__main__':
verify_demo()
# check_who_is()
参考:
吴恩达课后编程作业】Course 4 -卷积神经网络 - 第四周作业
如何在 Keras 中使用 FaceNet 开发人脸识别系统
32 声望
13 粉丝
推荐阅读
推荐系统评测指标
一. 评测指标用户满意度、预测准确度、覆盖率、多样性、 新颖性、惊喜度、信任度、实时性、健壮性、商业目标1. 用户满意度满意度是评测推荐系统的最重要指标,只能通过用户调查或者在线实验获得,主要是通过调查...
捕风阅读 602评论 1
python cv2去水印(百度百科)
原理是:用2张图片进行对比需要注意 我这个ddd.jpg是自己非专业P的图,正常应该是都是黑的背景然后logo和原图一样大小,2张图片需要一样的像素长宽
瑞0908赞 2阅读 2.1k
视频清晰度优化指南
随着移动互联网的深入发展,视频消费场景逐渐变成主流,早期由于手机硬件的限制问题,导致生产出来的视频画质、清晰度存在较大的问题,用户体验不太好,当时的网络也处于4G的发展阶段,网络的限制也无法持续支持...
得物技术赞 2阅读 896
MongoDB 插入时间与更新时间(create_time/update_time)
MongoDB 在数据库层面不能像 MySQL 一样设置自动创建 create_time/update_time,自动更新 update_time
qbit阅读 13.9k评论 2
“3D 元宇宙技术”在汽车新零售领域的应用与实践
随着不久前汽车之家新零售项目震撼发布,我们直击用户看车选车痛点首次提出 ABC 新体验模式,以元宇宙科技打造沉浸式交互服务,开放元宇宙能源空间站体验店,为用户打造更“有用”的体验。
之家技术阅读 5.2k
DeepMind 发布强化学习通用算法 DreamerV3,AI 成精自学捡钻石
内容一览:强化学习是多学科领域的交叉产物,其本质是实现自动决策且可做连续决策。本文将介绍 DeepMind 最新研发成果:扩大强化学习应用范围的通用算法 DreamerV3。关键词:强化学习 DeepMind 通用算法
超神经HyperAI赞 1阅读 476
AIGC神器CLIP:技术详解及应用示例
编者按:上一期,我们介绍了Diffusion模型的发展历程、核心原理及其对AIGC发展的推动作用。本期,我们将共同走进另一项AI重要突破——CLIP,著名的DALLE和Stable Diffusion均采用了CLIP哦。
Baihai_IDP赞 1阅读 938
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。