热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

简单的人脸识别

目录一、建立人脸数据集1.采集人脸2.采集对应20张图片的68个特征点数组和平均特征数组二、人脸识别总结参考资料接上一篇博客基于dlib+opencv3.4+python3.7的人




目录


  • 一、建立人脸数据集
    • 1.采集人脸
    • 2.采集对应20张图片的68个特征点数组和平均特征数组

  • 二、人脸识别
  • 总结
  • 参考资料


接上一篇博客基于dlib+opencv3.4+python3.7的人脸特征提取



一、建立人脸数据集

1.采集人脸

建立自己的人脸数据集:建议采集多角度的20张人脸

import cv2
import dlib
import os
import sys
import random
# 存储位置
output_dir = 'D:/631907060410/4me' #采集人脸的路径:其中4***为人名(英文方式)方便对比,第二次编译时修改为5***,进行多人比对
size = 100

if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 改变图片的亮度与对比度

def relight(img, light=1, bias=0):
w = img.shape[1]
h = img.shape[0]
#image = []
for i in range(0,w):
for j in range(0,h):
for c in range(3):
tmp = int(img[j,i,c]*light + bias)
if tmp > 255:
tmp = 255
elif tmp <0:
tmp = 0
img[j,i,c] = tmp
return img

#使用dlib自带的frontal_face_detector作为我们的特征提取器
detector = dlib.get_frontal_face_detector()
# 打开摄像头 参数为输入流,可以为摄像头或视频文件
camera = cv2.VideoCapture(0) #打开摄像头方式
#camera = cv2.VideoCapture('2.mp4') #采集视频的人脸
index = 1
while True:
if (index <= 20):#存储20张人脸特征图像
print('Being processed picture %s' % index)
# 从摄像头读取照片
success, img = camera.read()
# 转为灰度图片
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 使用detector进行人脸检测
dets = detector(gray_img, 1)

for i, d in enumerate(dets):
x1 = d.top() if d.top() > 0 else 0
y1 = d.bottom() if d.bottom() > 0 else 0
x2 = d.left() if d.left() > 0 else 0
y2 = d.right() if d.right() > 0 else 0

face = img[x1:y1,x2:y2]
# 调整图片的对比度与亮度, 对比度与亮度值都取随机数,这样能增加样本的多样性
face = relight(face, random.uniform(0.5, 1.5), random.randint(-50, 50))

face = cv2.resize(face, (size,size))

cv2.imshow('image', face)

cv2.imwrite(output_dir+'/'+str(index)+'.jpg', face)

index += 1
key = cv2.waitKey(30) & 0xff
if key == 27:
break
else:
print('Finished!')
# 释放摄像头 release camera
camera.release()
# 删除建立的窗口 delete all the windows
cv2.destroyAllWindows()
break

在这里插入图片描述

我采集了三组:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述


2.采集对应20张图片的68个特征点数组和平均特征数组

由于我采集了三组数据,所以会有60个数组(当然,如果有无效图的话就没有60组了)。


当光线过亮或者过暗,五官没有在采集到的图片内或模糊不清时,这张图就无效


from cv2 import cv2 as cv2
import os
import dlib
from skimage import io
import csv
import numpy as np

# 要读取人脸图像文件的路径
path_images_from_camera = "D:/631907060410/"
# Dlib 正向人脸检测器
detector = dlib.get_frontal_face_detector()
# Dlib 人脸预测器
predictor = dlib.shape_predictor("C:/Users/86150/JupyterProject/shape_predictor_68_face_landmarks.dat")
# Dlib 人脸识别模型
# Face recognition model, the object maps human faces into 128D vectors
face_rec = dlib.face_recognition_model_v1("C:/Users/86150/JupyterProject/dlib_face_recognition_resnet_model_v1.dat")
# 返回单张图像的 128D 特征
def return_128d_features(path_img):
img_rd = io.imread(path_img)
s=path_img
a=s[16:17]
i1=str(a)
a1=s[17:]
str1="/"
b=a1[a1.index(str1):-4]
b1=b[1:]
i2=str(b1)
img_gray = cv2.cvtColor(img_rd, cv2.COLOR_BGR2RGB)
faces = detector(img_gray, 1)
for i in range(len(faces)):
landmarks = np.matrix([[p.x, p.y] for p in predictor(img_rd,faces[i]).parts()])
for idx, point in enumerate(landmarks):
# 68点的坐标
pos = (point[0, 0], point[0, 1])
add="D:/631907060410/face"+i1+"_feature"+i2+".csv"
with open(add, "a", newline="") as csvfile:
writer1 = csv.writer(csvfile)
writer1.writerow((idx,pos))
print(add)
print("%-40s %-20s" % ("检测到人脸的图像 / image with faces detected:", path_img), '\n')
# 因为有可能截下来的人脸再去检测,检测不出来人脸了
# 所以要确保是 检测到人脸的人脸图像 拿去算特征
if len(faces) != 0:
shape = predictor(img_gray, faces[0])
face_descriptor = face_rec.compute_face_descriptor(img_gray, shape)
else:
face_descriptor = 0
print("no face")
return face_descriptor
# 将文件夹中照片特征提取出来, 写入 CSV
def return_features_mean_personX(path_faces_personX):
features_list_persOnX= []
photos_list = os.listdir(path_faces_personX)
if photos_list:
for i in range(len(photos_list)):
# 调用return_128d_features()得到128d特征
print("%-40s %-20s" % ("正在读的人脸图像 / image to read:", path_faces_personX + "/" + photos_list[i]))
features_128d = return_128d_features(path_faces_personX + "/" + photos_list[i])
# print(features_128d)
# 遇到没有检测出人脸的图片跳过
if features_128d == 0:
i += 1
else:
features_list_personX.append(features_128d)
else:
print("文件夹内图像文件为空 / Warning: No images in " + path_faces_personX + '/', '\n')
# 计算 128D 特征的均值
# N x 128D -> 1 x 128D
if features_list_personX:
features_mean_persOnX= np.array(features_list_personX).mean(axis=0)
else:
features_mean_persOnX= '0'
return features_mean_personX
# 读取某人所有的人脸图像的数据
people = os.listdir(path_images_from_camera)
people.sort()
with open("D:/631907060410/face_feature_mean.csv", "w", newline="") as csvfile: #程序会新建一个表格文件来保存特征值,方便以后比对
writer = csv.writer(csvfile)
for person in people:
print("##### " + person + " #####")
# Get the mean/average features of face/personX, it will be a list with a length of 128D
features_mean_persOnX= return_features_mean_personX(path_images_from_camera + person)
writer.writerow(features_mean_personX)
print("特征均值 / The mean of features:", list(features_mean_personX))
print('\n')
print("所有录入人脸数据存入 / Save all the features of faces registered into: D:/631907060410face_feature_mean.csv")

在这里插入图片描述

生成的60组特征点数组和平均特征数组
在这里插入图片描述

特征点数组(以face2_feature1.csv为例):
在这里插入图片描述
平均特征值:
在这里插入图片描述


二、人脸识别

import os
import winsound # 系统音效
from playsound import playsound # 音频播放
import dlib # 人脸处理的库 Dlib
import csv # 存入表格
import time
import sys
import numpy as np # 数据处理的库 numpy
from cv2 import cv2 as cv2 # 图像处理的库 OpenCv
import pandas as pd # 数据处理的库 Pandas
# 人脸识别模型,提取128D的特征矢量
# face recognition model, the object maps human faces into 128D vectors
# Refer this tutorial: http://dlib.net/python/index.html#dlib.face_recognition_model_v1
facerec = dlib.face_recognition_model_v1("C:/Users/86150/JupyterProject/dlib_face_recognition_resnet_model_v1.dat")#我这是在同一路径下的,dlib_face_recognition_resnet_model_v1.dat不在
#要写为绝对路径:"D:/****/****/dlib_face_recognition_resnet_model_v1.dat"
# 计算两个128D向量间的欧式距离
# compute the e-distance between two 128D features
def return_euclidean_distance(feature_1, feature_2):
feature_1 = np.array(feature_1)
feature_2 = np.array(feature_2)
dist = np.sqrt(np.sum(np.square(feature_1 - feature_2)))
return dist
# 处理存放所有人脸特征的 csv
path_features_known_csv = "D:/631907060410/face_feature_mean.csv"
csv_rd = pd.read_csv(path_features_known_csv, header=None)
# 用来存放所有录入人脸特征的数组
# the array to save the features of faces in the database
features_known_arr = []
# 读取已知人脸数据
# print known faces
for i in range(csv_rd.shape[0]):
features_someone_arr = []
for j in range(0, len(csv_rd.ix[i, :])):
features_someone_arr.append(csv_rd.ix[i, :][j])
features_known_arr.append(features_someone_arr)
print("Faces in Database:", len(features_known_arr))
# Dlib 检测器和预测器
# The detector and predictor will be used
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('C:/Users/86150/JupyterProject/shape_predictor_68_face_landmarks.dat')#我这是在同一路径下的,shape_predictor_68_face_landmarks.dat不在
#要写为绝对路径:"D:/****/****/shape_predictor_68_face_landmarks.dat
# 创建 cv2 摄像头对象
# cv2.VideoCapture(0) to use the default camera of PC,
# and you can use local video name by use cv2.VideoCapture(filename)
cap = cv2.VideoCapture(0)
# cap.set(propId, value)
# 设置视频参数,propId 设置的视频参数,value 设置的参数值
cap.set(3, 480)
# cap.isOpened() 返回 true/false 检查初始化是否成功
# when the camera is open
while cap.isOpened():
flag, img_rd = cap.read()
kk = cv2.waitKey(1)
# 取灰度
img_gray = cv2.cvtColor(img_rd, cv2.COLOR_RGB2GRAY)
# 人脸数 faces
faces = detector(img_gray, 0)
# 待会要写的字体 font to write later
fOnt= cv2.FONT_HERSHEY_COMPLEX
# 存储当前摄像头中捕获到的所有人脸的坐标/名字
# the list to save the positions and names of current faces captured
pos_namelist = []
name_namelist = []
# 按下 q 键退出
# press 'q' to exit
if kk == ord('q'):
break
else:
# 检测到人脸 when face detected
if len(faces) != 0:
# 获取当前捕获到的图像的所有人脸的特征,存储到 features_cap_arr
# get the features captured and save into features_cap_arr
features_cap_arr = []
for i in range(len(faces)):
shape = predictor(img_rd, faces[i])
features_cap_arr.append(facerec.compute_face_descriptor(img_rd, shape))
# 遍历捕获到的图像中所有的人脸
# traversal all the faces in the database
for k in range(len(faces)):
print("##### camera person", k+1, "#####")
# 让人名跟随在矩形框的下方
# 确定人名的位置坐标
# 先默认所有人不认识,是 unknown
# set the default names of faces with "unknown"
name_namelist.append("unknown")
# 每个捕获人脸的名字坐标 the positions of faces captured
pos_namelist.append(tuple([faces[k].left(), int(faces[k].bottom() + (faces[k].bottom() - faces[k].top())/4)]))
# 对于某张人脸,遍历所有存储的人脸特征
# for every faces detected, compare the faces in the database
e_distance_list = []
for i in range(len(features_known_arr)):
# 如果 person_X 数据不为空
if str(features_known_arr[i][0]) != '0.0':
print("with person", str(i + 1), "the e distance: ", end='')
e_distance_tmp = return_euclidean_distance(features_cap_arr[k], features_known_arr[i])
print(e_distance_tmp)
e_distance_list.append(e_distance_tmp)
else:
# 空数据 person_X
e_distance_list.append(999999999)
# 找出最接近的一个人脸数据是第几个
# Find the one with minimum e distance
similar_person_num = e_distance_list.index(min(e_distance_list))
print("Minimum e distance with person", int(similar_person_num)+1)

# 计算人脸识别特征与数据集特征的欧氏距离
# 距离小于0.4则标出为可识别人物
if min(e_distance_list) <0.4:
# 这里可以修改摄像头中标出的人名
# Here you can modify the names shown on the camera
# 1、遍历文件夹目录
folder_name = 'D:/631907060410'
# 最接近的人脸
sum=similar_person_num+1
key_id=1 # 从第一个人脸数据文件夹进行对比
# 获取文件夹中的文件名:1wang、2zhou、3...
file_names = os.listdir(folder_name)
for name in file_names:
# print(name+'->'+str(key_id))
if sum ==key_id:
#winsound.Beep(300,500)# 响铃:300频率,500持续时间
name_namelist[k] = name[1:]#人名删去第一个数字(用于视频输出标识)
key_id += 1
# 播放欢迎光临音效
#playsound('D:/myworkspace/JupyterNotebook/People/music/welcome.wav')
# print("May be person "+str(int(similar_person_num)+1))
# -----------筛选出人脸并保存到visitor文件夹------------
for i, d in enumerate(faces):
x1 = d.top() if d.top() > 0 else 0
y1 = d.bottom() if d.bottom() > 0 else 0
x2 = d.left() if d.left() > 0 else 0
y2 = d.right() if d.right() > 0 else 0
face = img_rd[x1:y1,x2:y2]
size = 64
face = cv2.resize(face, (size,size))
# 要存储visitor人脸图像文件的路径
path_visitors_save_dir = "D:/face/known" #自己在faces路径下先建一个known文件,否则可能会报错
# 存储格式:2019-06-24-14-33-40wang.jpg
now_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
save_name = str(now_time)+str(name_namelist[k])+'.jpg'
# print(save_name)
# 本次图片保存的完整url
save_path = path_visitors_save_dir+'/'+ save_name
# 遍历visitor文件夹所有文件名
visitor_names = os.listdir(path_visitors_save_dir)
visitor_name=''
for name in visitor_names:
# 名字切片到分钟数:2019-06-26-11-33-00wangyu.jpg
visitor_name=(name[0:16]+'-00'+name[19:])
# print(visitor_name)
visitor_save=(save_name[0:16]+'-00'+save_name[19:])
# print(visitor_save)
# 一分钟之内重复的人名不保存
if visitor_save!=visitor_name:
cv2.imwrite(save_path, face)
print('新存储:'+path_visitors_save_dir+'/'+str(now_time)+str(name_namelist[k])+'.jpg')
else:
print('重复,未保存!')

else:
# 播放无法识别音效
#playsound('D:/myworkspace/JupyterNotebook/People/music/sorry.wav')
print("Unknown person")
# -----保存图片-------
# -----------筛选出人脸并保存到visitor文件夹------------
for i, d in enumerate(faces):
x1 = d.top() if d.top() > 0 else 0
y1 = d.bottom() if d.bottom() > 0 else 0
x2 = d.left() if d.left() > 0 else 0
y2 = d.right() if d.right() > 0 else 0
face = img_rd[x1:y1,x2:y2]
size = 64
face = cv2.resize(face, (size,size))
# 要存储visitor-》unknown人脸图像文件的路径
path_visitors_save_dir = "D:/face/unknown"#自己在faces路径下先建一个unknown文件,否则可能会报错
# 存储格式:2019-06-24-14-33-40unknown.jpg
now_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
# print(save_name)
# 本次图片保存的完整url
save_path = path_visitors_save_dir+'/'+ str(now_time)+'unknown.jpg'
cv2.imwrite(save_path, face)
print('新存储:'+path_visitors_save_dir+'/'+str(now_time)+'unknown.jpg')

# 矩形框
# draw rectangle
for kk, d in enumerate(faces):
# 绘制矩形框
cv2.rectangle(img_rd, tuple([d.left(), d.top()]), tuple([d.right(), d.bottom()]), (0, 255, 255), 2)
print('\n')
# 在人脸框下面写人脸名字
# write names under rectangle
for i in range(len(faces)):
cv2.putText(img_rd, name_namelist[i], pos_namelist[i], font, 0.8, (0, 255, 255), 1, cv2.LINE_AA)
print("Faces in camera now:", name_namelist, "\n")
#cv2.putText(img_rd, "Press 'q': Quit", (20, 450), font, 0.8, (84, 255, 159), 1, cv2.LINE_AA)
cv2.putText(img_rd, "Face Recognition", (20, 40), font, 1, (0, 0, 255), 1, cv2.LINE_AA)
cv2.putText(img_rd, "Visitors: " + str(len(faces)), (20, 100), font, 1, (0, 0, 255), 1, cv2.LINE_AA)
# 窗口显示 show with opencv
cv2.imshow("camera", img_rd)
k = cv2.waitKey(1)
if k == 27: # press 'ESC' to quit
break
# 释放摄像头 release camera
cap.release()
# 删除建立的窗口 delete all the windows
cv2.destroyAllWindows()

在这里插入图片描述

人脸识别成功:
选了两张采集时没有采集到文件的照片测试
在这里插入图片描述

在这里插入图片描述
成功识别。


总结

人脸识别首先要采集人脸特征,识别时程序会根据20张人脸的特征均值作对比,小于0.4时判定为同一人,超出0.4,判定为unkown。


参考资料

https://blog.csdn.net/jaray/article/details/108887695
https://blog.csdn.net/qq_43279579/article/details/117637044



推荐阅读
  • python3 nmap函数简介及使用方法
    本文介绍了python3 nmap函数的简介及使用方法,python-nmap是一个使用nmap进行端口扫描的python库,它可以生成nmap扫描报告,并帮助系统管理员进行自动化扫描任务和生成报告。同时,它也支持nmap脚本输出。文章详细介绍了python-nmap的几个py文件的功能和用途,包括__init__.py、nmap.py和test.py。__init__.py主要导入基本信息,nmap.py用于调用nmap的功能进行扫描,test.py用于测试是否可以利用nmap的扫描功能。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文讨论了在openwrt-17.01版本中,mt7628设备上初始化启动时eth0的mac地址总是随机生成的问题。每次随机生成的eth0的mac地址都会写到/sys/class/net/eth0/address目录下,而openwrt-17.01原版的SDK会根据随机生成的eth0的mac地址再生成eth0.1、eth0.2等,生成后的mac地址会保存在/etc/config/network下。 ... [详细]
  • 本文介绍了Python爬虫技术基础篇面向对象高级编程(中)中的多重继承概念。通过继承,子类可以扩展父类的功能。文章以动物类层次的设计为例,讨论了按照不同分类方式设计类层次的复杂性和多重继承的优势。最后给出了哺乳动物和鸟类的设计示例,以及能跑、能飞、宠物类和非宠物类的增加对类数量的影响。 ... [详细]
  • 基于词向量计算文本相似度1.测试数据:链接:https:pan.baidu.coms1fXJjcujAmAwTfsuTg2CbWA提取码:f4vx2.实验代码:imp ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • 本文分享了一个关于在C#中使用异步代码的问题,作者在控制台中运行时代码正常工作,但在Windows窗体中却无法正常工作。作者尝试搜索局域网上的主机,但在窗体中计数器没有减少。文章提供了相关的代码和解决思路。 ... [详细]
  • Webpack5内置处理图片资源的配置方法
    本文介绍了在Webpack5中处理图片资源的配置方法。在Webpack4中,我们需要使用file-loader和url-loader来处理图片资源,但是在Webpack5中,这两个Loader的功能已经被内置到Webpack中,我们只需要简单配置即可实现图片资源的处理。本文还介绍了一些常用的配置方法,如匹配不同类型的图片文件、设置输出路径等。通过本文的学习,读者可以快速掌握Webpack5处理图片资源的方法。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • Android JSON基础,音视频开发进阶指南目录
    Array里面的对象数据是有序的,json字符串最外层是方括号的,方括号:[]解析jsonArray代码try{json字符串最外层是 ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • Flink使用java实现读取csv文件简单实例首先我们来看官方文档中给出的几种方法:首先我们来看官方文档中给出的几种方法:第一种:Da ... [详细]
  • 如何在mysqlshell命令中执行sql命令行本文介绍MySQL8.0shell子模块Util的两个导入特性importTableimport_table(JS和python版本 ... [详细]
  • 简介数组、CSV、表格、东西将一个数组转化为逗号为支解符的字符串(CSV)即表格数据。该源码来自于https:30secondsofcode.orgconstarrayToCSV( ... [详细]
  • 用pandas库修改excel文件里的内容,并把excel文件格式存为csv格式,再将csv格式改为html格式
    假设有Excel文件data.xlsx,其中内容为:     ID age height    sex weight张三  1  39    181 female     85李四  2  40    180   male     80王五  3  38    178 female     78赵六  4  59    1 ... [详细]
author-avatar
耿睿---疯子
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有