文章内容:
一、人脸识别数据集的建立。利用dlib和opencv编程: 1)采集自己的脸部图片20张,保存到以学号命名的文件目录下;2)采集对应20张图片的68个特征点数组,以 face_features.txt (i为01到20的数字)文件保存到同一目录下;3)通过20个特征,计算出平均(mean)特征数组 face_feature_mean.txt.
二、利用dlib和opencv编程,打开摄像头,对捕获到的人脸进行特征提取,与平均特征进行误差计算(欧几里得距离),当误差小于一定阈值时,判断为同一个人,否则判断为 unknown。

嘿!我是目录

  • 一、采集脸部图片二十张
    • 1.1 库文件准备
    • 1.2 录入人脸数据
      • 1.2.1 代码
      • 1.2.2 运行结果
  • 二、构建数据集
    • 2.1 dlib人脸特征检测原理
    • 2.2 采集特征点数组,计算平均特征数组
      • 2.2.1 代码
      • 2.2.2 运行结果
  • 三、人脸识别
    • 3.1 代码:
    • 3.2 运行结果
  • 小小的总结
  • 参考文献

一、采集脸部图片二十张

1.1 库文件准备

  • 首先我们需要准备两个库文件
  • 一是: dlib_face_recognition_resnet_model_v1.dat
    百度网盘下载链接:
    链接:https://pan.baidu.com/s/1tPt6JaAoksUKBm0MVO248A
    提取码:0000
  • 二是: shape_predictor_68_face_landmarks.dat
    百度网盘下载链接:
    链接:https://pan.baidu.com/s/1_I0Z5WLpKb-w6IWjH-RIgQ
    提取码:0001
  • 下载后放到一个文件夹里,这个文件路径等会儿我们在代码中是要用的。

1.2 录入人脸数据

1.2.1 代码

  • 打开Acaconda3 的 Jupyter Notebook
  • 输入代码:
  • 一定要注意文件路径,改为自己的路径。

import cv2
import dlib
import os
import sys
import random
# 存储位置
output_dir = 'D:/myworkspace/JupyterNotebook/People/person/person1/631907060228/1'
size = 64if 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 = 255elif tmp < 0:tmp = 0img[j,i,c] = tmpreturn img#使用dlib自带的frontal_face_detector作为我们的特征提取器
detector = dlib.get_frontal_face_detector()
# 打开摄像头 参数为输入流,可以为摄像头或视频文件
camera = cv2.VideoCapture(0)
#camera = cv2.VideoCapture('C:/Users/CUNGU/Videos/Captures/wang.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 0y1 = d.bottom() if d.bottom() > 0 else 0x2 = d.left() if d.left() > 0 else 0y2 = d.right() if d.right() > 0 else 0face = 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 += 1key = cv2.waitKey(30) & 0xffif key == 27:breakelse:print('Finished!')# 释放摄像头 release cameracamera.release()# 删除建立的窗口 delete all the windowscv2.destroyAllWindows()break

1.2.2 运行结果

  • 在对应的文件下找到,即可看到截取的20张人脸:

二、构建数据集

采集对应20张图片的68个特征点数组,以 face_features.txt (i为01到20的数字)文件保存到同一目录下。通过20个特征,计算出平均(mean)特征数组 face_feature_mean.csv。

2.1 dlib人脸特征检测原理

  1. 提取特征点:
    例:

  2. 将特征值保存到CSV文件

  3. 计算特征数据集的欧氏距离作对比,当误差小于一定阙值就判定为同一人。

2.2 采集特征点数组,计算平均特征数组

2.2.1 代码

# 从人脸图像文件中提取人脸特征存入 CSV
# Features extraction from images and save into features_all.csv# return_128d_features()          获取某张图像的128D特征
# compute_the_mean()              计算128D特征均值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:/myworkspace/JupyterNotebook/People/person/person1/631907060228/"# Dlib 正向人脸检测器
detector = dlib.get_frontal_face_detector()# Dlib 人脸预测器
predictor = dlib.shape_predictor("D:/ProgramData/wenjian/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("D:/ProgramData/wenjian/dlib_face_recognition_resnet_model_v1.dat")# 返回单张图像的 128D 特征
def return_128d_features(path_img):img_rd = io.imread(path_img)img_gray = cv2.cvtColor(img_rd, cv2.COLOR_BGR2RGB)faces = detector(img_gray, 1)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 = 0print("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 += 1else:features_list_personX.append(features_128d)i1=str(i+1)add="D:/myworkspace/JupyterNotebook/People/person/person1/631907060228/csv/"+"face_features"+i1+".csv"print(add)with open(add, "w", newline="") as csvfile:writer1 = csv.writer(csvfile)writer1.writerow(features_128d)else:print("文件夹内图像文件为空 / Warning: No images in " + path_faces_personX + '/', '\n')# 计算 128D 特征的均值# N x 128D -> 1 x 128Dif 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:/myworkspace/JupyterNotebook/People/person/person1/631907060228/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 128Dfeatures_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:/myworkspace/JupyterNotebook/People/person/person1/631907060228/face_feature_mean.csv")

2.2.2 运行结果

  • 在对应的文件下找到,即可看到采集特征点数组与平均特征数组的.csv文件


三、人脸识别

利用dlib和opencv编程,打开摄像头,对捕获到的人脸进行特征提取,与平均特征进行误差计算(欧几里得距离),当误差小于一定阈值时,判断为同一个人,否则判断为 unknown。

3.1 代码:

# 摄像头实时人脸识别
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("D:/ProgramData/wenjian/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:/myworkspace/JupyterNotebook/People/person/person1/631907060228/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.iloc[i, :])):features_someone_arr.append(csv_rd.iloc[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('D:/ProgramData/wenjian/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)# 人脸数 facesfaces = detector(img_gray, 0)# 待会要写的字体 font to write laterfont = cv2.FONT_HERSHEY_COMPLEX# 存储当前摄像头中捕获到的所有人脸的坐标/名字# the list to save the positions and names of current faces capturedpos_namelist = []name_namelist = []# 按下 q 键退出# press 'q' to exitif kk == ord('q'):breakelse:# 检测到人脸 when face detectedif len(faces) != 0:  # 获取当前捕获到的图像的所有人脸的特征,存储到 features_cap_arr# get the features captured and save into features_cap_arrfeatures_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 databasefor 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 capturedpos_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 databasee_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_Xe_distance_list.append(999999999)# 找出最接近的一个人脸数据是第几个# Find the one with minimum e distancesimilar_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:/myworkspace/JupyterNotebook/People/person/person1/631907060228/'# 最接近的人脸sum=similar_person_num+1key_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[0:]#人名删去第一个数字(用于视频输出标识)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 0y1 = d.bottom() if d.bottom() > 0 else 0x2 = d.left() if d.left() > 0 else 0y2 = d.right() if d.right() > 0 else 0face = img_rd[x1:y1,x2:y2]size = 64face = cv2.resize(face, (size,size))# 要存储visitor人脸图像文件的路径path_visitors_save_dir = "D:/myworkspace/JupyterNotebook/People/person/person1/visitor/known"# 存储格式:2019-06-24-14-33-40wang.jpgnow_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())save_name = str(now_time)+str(name_namelist[k])+'.jpg'# print(save_name)# 本次图片保存的完整urlsave_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.jpgvisitor_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 0y1 = d.bottom() if d.bottom() > 0 else 0x2 = d.left() if d.left() > 0 else 0y2 = d.right() if d.right() > 0 else 0face = img_rd[x1:y1,x2:y2]size = 64face = cv2.resize(face, (size,size))# 要存储visitor-》unknown人脸图像文件的路径path_visitors_save_dir = "D:/myworkspace/JupyterNotebook/People/person/person1/visitor/unknown"# 存储格式:2019-06-24-14-33-40unknown.jpgnow_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())# print(save_name)# 本次图片保存的完整urlsave_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 rectanglefor 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 rectanglefor 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 opencvcv2.imshow("camera", img_rd)# 释放摄像头 release camera
cap.release()# 删除建立的窗口 delete all the windows
cv2.destroyAllWindows()

3.2 运行结果

  • 识别出后显示1:

  • 未识别出显示unknown:

小小的总结

建议人脸录入、构建人脸数据集和人脸识别 三个部分分别用不同的 Jupyter Notebook 的新建的Python3来运行,会不容易出错一点,也更容易排错。

此次实验还挺有趣的,录入人脸,分析图片,获得数据,就可以人脸识别了,看似简单,其实不然。人脸识别,要先识别出人脸,再识别出是不是你。

在运行人脸检测识别代码时,可能不知道如何退出,方法:按 q/Q 退出。

参考文献

  1. 人脸识别数据集建立及应用
  2. Dlib模型人脸特征检测原理及demo
  3. 基于dlib库人脸特征提取【构建自己的人脸识别数据集】

人脸识别数据集的建立(dlib+opencv)及人脸识别相关推荐

  1. python表情识别程序_Python+Dlib+Opencv实现人脸采集并表情判别功能的代码

    一.dlib以及opencv-python库安装 介于我使用的是jupyter notebook,所以在安装dlib和opencv-python时是在 这个命令行安装的 dlib安装方法: 1.若可以 ...

  2. 基于TensorFlow深度学习框架,运用python搭建LeNet-5卷积神经网络模型和mnist手写数字识别数据集,设计一个手写数字识别软件。

    本软件是基于TensorFlow深度学习框架,运用LeNet-5卷积神经网络模型和mnist手写数字识别数据集所设计的手写数字识别软件. 具体实现如下: 1.读入数据:运用TensorFlow深度学习 ...

  3. 人脸识别数据集的建立及应用

    目录 一.相关文件下载及配置 二.数据集的建立 1.录入图片 2. 提取每张图片的特征值和特征均值 三.应用 四.参考 一.相关文件下载及配置 dlib 的配置 参考python3+opencv3.4 ...

  4. flutter 人脸检测_【转载】opencv实现人脸检测

    全文转载自CSDN的博客(不知道怎么将CSDN的博客转到博客园,应该没这功能吧,所以直接复制全文了),转载地址如下 http://blog.csdn.net/lsq2902101015/article ...

  5. android opencv 银行卡识别,NDK 开发之使用 OpenCV 实现银行卡号识别

    前言 在日常的开发中,我们有时会遇到添加银行卡的需求,这时候,产品可能会让你仿一下支付宝之类的相机扫描识别银行卡号.很多时候,做这样的需求会去找找稳定的第三方,本文通过 OpenCV 结合识别的需求带 ...

  6. python人脸识别opencv_用python和opencv 做人脸识别

    网上找的代码,运行之后,发现没有描述的功能.test1窗口打开之后,并不能识别人脸.本人初学,希望大家不吝赐教,在此谢过 import cv2 import numpy as np cv2.named ...

  7. Python人脸微笑识别2-----Ubuntu16.04基于Tensorflow卷积神经网络模型训练的Python3+Dlib+Opencv实现摄像头人脸微笑检测

    Python人脸微笑识别2--卷积神经网络进行模型训练目录 一.微笑数据集下载 1.微笑数据集下载 2.创建人脸微笑识别项目 3.数据集上传至Ubuntu人脸微笑识别项目文件夹 二.Python代码实 ...

  8. Python基于OpenCV的人脸表情识别系统[源码&部署教程]

    1.项目背景 人脸表情识别是模式识别中一个非常重要却十分复杂的课题.首先对计算机人脸表情识别技术的研究背景及发展历程作了简单回顾.然后对近期人脸表情识别的方法进行了分类综述.通过对各种识别方法的分析与 ...

  9. 【OpenCV】人脸检测和识别

    文章目录 前言 一.人脸检测 1.基于Haar的人脸检测 2.基于深度学习的人脸检测 二.人脸识别 1.特征脸EigenFaces 2.人鱼脸FisherFaces 3.局部二进制编码直方图LBPH ...

  10. 使用opencv制作人脸识别小软件

    正文: 1.既然说做个小软件那就,先做个简单的软件封面. 随便找一个图片,然后手动画上自己需要的按钮,然后设置鼠标反应. 画按钮: void buttonset() {rectangle(image, ...

最新文章

  1. 网络营销过程中如何避免网站的过度优化情况的发生?
  2. citrix xenapp应用保存文件时隐藏服务器上的磁盘
  3. 在mybatis中调oracle dblink存储过程
  4. Coolite 基本用法(3)
  5. [转载] python判断字符串中包含某个字符串_干货分享| Python中最常用的字符串方法
  6. 八种点云聚类方法(一)— DBSCAN
  7. ai的预览模式切换_ai全屏快捷键是什么(Ai切换屏幕模式有哪些)
  8. python字符串格式化是什么意思_Python字符串格式化中%s和%d之间有什么区别?...
  9. douban movie top of Web Crawler
  10. Arturia Sound Explorers Collection Belledonne现已上市
  11. 《机器学习实战》(七)-- LinearRegression
  12. 4.4.1. SWE.1 Software Requirements Analysis中“Process outcomes”的第一条的正确翻译
  13. CodeForces - 743B
  14. 如何用Modis模拟WAP上网
  15. Halo 开源项目学习(五):评论与点赞
  16. duilib 动态多语言支持
  17. *迟来的爱*——《Foursquare》应用源码学习(一) 下载、编译、运行
  18. Python3 读取本地、网络摄像头流
  19. 解决request fail url is not in domain,不在以下 request 合法域名列表中
  20. 超融合集群数据分布原理

热门文章

  1. 携程合体去哪儿,与途牛度假旅游市场争高下
  2. 韩剧爱情需要奇迹剧情在线
  3. protoc 命令 java_protoc 指令介绍
  4. Centos 8 阿里yum源配置
  5. java基础题100道
  6. 关于扩展欧几里得算法的证明
  7. 嵌入式Linux应用程序开发
  8. LCD驱动芯片/LCD段式液晶显示驱动芯片-VK0192M/VK0256/B/C技术资料简介
  9. 安卓app逆向破解脱壳教程
  10. 计算机跳过密码直接登录密码,win10免密码自动登录怎么设置_win10跳过密码直接登录电脑-win7之家...