目录

一、人脸识别数据集

二、总结


一、人脸识别数据集

1、采集自己的脸部图片15张,保存到文件夹中

代码

import cv2
import dlib
import os
import sys
import random
# 存储位置
output_dir = 'D:/D:\picture\person1'
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('D:/z7z8/yy.mp4')index = 1
while True:if (index <= 15):#存储15张人脸特征图像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

2.分别将每张图片的特征点数组保存到一个独立的表格,通过20张图片的特征,计算出平均特征并保存到表格

人脸识别数据集采集

# 从人脸图像文件中提取人脸特征存入 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:/picture/person1"# Dlib 正向人脸检测器
detector = dlib.get_frontal_face_detector()# Dlib 人脸预测器
predictor = dlib.shape_predictor("D:/picture/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:/picture/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:/renlianshibie/face_feature"+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/feature/features2_all.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/feature/features_all2.csv")

3.通过已经保存的数据,打开摄像头,对捕获到的人脸进行特征提取,与平均特征进行误差计算(欧几里得距离),当误差小于一定阈值时,判断为同一个人,否则判断为 unknown。

# 摄像头实时人脸识别
import os
import winsound # 系统音效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:/picture/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:/renlianshibie/features00_all.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:/picture/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:/picture/person1'# 最接近的人脸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:/picture/person1/visitor"# 存储格式: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:/picture/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()

运行结果

二、总结

通过本次实验,熟悉了人脸特征值提取的基本步骤,进一步了解了dlib库和OpenCV的使用原理,实现了简单的人脸识别功能。

人脸识别数据集的采集相关推荐

  1. 人脸识别数据集精粹(下)

    人脸识别数据集精粹(下) 人脸检测数据集 所谓人脸检测任务,就是要定位出图像中人脸的大概位置.通常检测完之后根据得到的框再进行特征的提取,包括关键点等信息,然后做一系列后续的分析. (1) Calte ...

  2. 人脸识别数据集精粹(上)

    人脸识别数据集精粹(上) 人脸识别 人脸检测和关键点检测都是比较底层的任务,而人脸识别是更高层的任务,它就是要识别出检测出来的人脸是谁,完成身份比对等任务,也是人脸领域里被研究最多的任务. 1.1 人 ...

  3. 微软删除最大的公开人脸识别数据集,只因员工离职?!

    作者 | 神经小姐姐 责编 | 郭芮 本文经授权转自HyperAI超神经(ID:HyperAI) 前几日,微软静悄悄地删除了一个公开的名人图片数据集.这个本为世界上最大的公开人脸识别数据集,现在已经不 ...

  4. 南京大学发布WebCaricature漫画人脸识别数据集

    近日,南京大学推理与学习研究组(R&L Group)发布了一个新的漫画人脸识别数据集 WebCaricature.该数据集包含了 252 个名人的 6042 幅漫画图像以及 5974 幅人脸图 ...

  5. 苹果宣布加入CNCF;华为要求美国运营商支付专利费;微软删除最大的公开人脸识别数据集...

    戳蓝字"CSDN云计算"关注我们哦! 嗨,大家好,重磅君带来的[云重磅]特别栏目,如期而至,每周五第一时间为大家带来重磅新闻.把握技术风向标,了解行业应用与实践,就交给我重磅君吧! ...

  6. 【数据集NO.3】人脸识别数据集汇总

    文章目录 前言 一.IMDB-WIKI人脸数据集 二.WiderFace人脸检测数据集 三.GENKI 人脸图像数据集 四.哥伦比亚大学公众人物脸部数据库 五.CelebA人脸数据集 六.美国国防部人 ...

  7. 人脸识别数据集整理以及下载

    人脸识别数据集整理 下方是整理的人脸识别数据集列表,有需要的小伙伴下载获取,仅限学习交流,不能用作他处,感谢理解. 下载链接:https://download.csdn.net/download/m0 ...

  8. 百度AI开放平台集成人脸识别,离线采集有动作活体版本sdk

    前言 Android项目Android studio环境: 1.工程build.gradle版本号:3.2.1 2.app目录下的build.gradle配置:compileSdkVersion 28 ...

  9. python构造自定义数据包_构建自定义人脸识别数据集的三种训练方法

    在接下来的几篇文章中,我们将训练计算机视觉+深度学习模型来进行面部识别.在此之前,我们首先需要收集脸部数据集. 如果你已经在使用预先准备好的数据集,比如Labeled Faces in the Wil ...

  10. 格灵深瞳开源全球最大最干净的人脸识别数据集:Glint360K

    本文转载自知乎,已获作者授权转载. 链接:https://zhuanlan.zhihu.com/p/265673438    1.数据集的表现 学术界的测评比如IJB-C和megaface,利用该数据 ...

最新文章

  1. 再见!Kafka决定弃用Zookeeper...
  2. Android Studio 多渠道打包
  3. 用C++的类重载高精度加法,乘法和等于符号
  4. [转]Delphi 2010 3513正式版破解
  5. Lr中脚本的迭代次数和场景运行时间的关系
  6. C++模板的那丢丢事儿
  7. mysql索引创建和使用注意事项
  8. Apriori算法实现
  9. Educational Codeforces Round 25 E. Minimal Labelshdu1258
  10. Python线程类首先是一个类
  11. Java 8 (5) Stream 流 - 收集数据
  12. Windows下anyproxy的配置文件路径
  13. 路由器访问控制列表详解
  14. 高富帅与大公司 续三 自我认知
  15. ARC_x86_OS选择
  16. 绝对路径、相对路径详解
  17. SpringMVC-视图和视图解析器
  18. android输入法好用,安卓手机输入法哪个最好用?
  19. 如何搭建 MTK 6577模拟器
  20. 创立10年,已成为自助建站翘楚的 Squarespace .这五大成功经验.

热门文章

  1. 不通过App Store实现ios应用分发下载安装
  2. 微信小程序上传图片到阿里云存储
  3. 虚拟文件系统VSF的作用
  4. smile——Java机器学习引擎
  5. 获取键盘上某键的状态
  6. 爬虫爬取数据时如何快速换IP?极光IP轻松搞定
  7. c语言编程软件支持win8,C语言编程软件vc6.0(支持win7 / win8 / 10)官方免费版6.0
  8. linux运行程音乐软件,在Linux系统下用Wine 5.0运行酷狗音乐的使用体验
  9. 模型预测控制(MPC)解析(一):模型
  10. java将pdf转excel,excel转pdf,itextpdf转换excel