人脸识别+数据采集+人脸特征提取(哈哈哈,绝决子)

本文主要是介绍人脸识别+数据采集+人脸特征提取(哈哈哈,绝决子),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

人脸识别+数据采集+人脸特征提取(哈哈哈,绝绝子)

1.实验效果
  • 根据采集的照片进行特征提取识别出人,效果还不错

在这里插入图片描述


2.基本需要

python 3.6

dlib 19.7.0

pycharm

dlib下载可以去看我的这个python3.8+pycharm下载dlib(搞了好久,终于好了)_Hulk_liu的博客-CSDN博客_python下载dlib

哈哈哈,夸我,now,说完咱就开始把


3.开始实验
3.1人脸采集
import cv2
import dlib
import os
import sys
import random# 存储位置
output_dir = './data/2***'  # 这里填编号+人名(例如1某某某,2某某)
size = 256  # 图片边长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 = 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):  # 存储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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sDrIM8Jw-1649990042671)(人脸识别+数据采集+人脸特征提取(哈哈哈,绝决子).assets/image-20220415095436712.png)]

  • 这里获取一个人大概20个人脸,我大概采集了20多个人,效果也可以实现

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zENPzIab-1649990042671)(人脸识别+数据采集+人脸特征提取(哈哈哈,绝决子).assets/image-20220415095606679.png)]

3.2人脸特征提取
# 从人脸图像文件中提取人脸特征存入 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 = "./data/"# Dlib 正向人脸检测器
detector = dlib.get_frontal_face_detector()# Dlib 人脸预测器
predictor = dlib.shape_predictor("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("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)):with open("./feature/featuresGiao"+str(i)+".csv", "w", newline="") as csvfile:writer = csv.writer(csvfile)# 调用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)writer.writerow(features_128d)# 遇到没有检测出人脸的图片跳过if features_128d == 0:i += 1else:features_list_personX.append(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("./feature/features_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: ./feature/features_all2.csv")
  • 这一步会讲特征提取放到feature里面,然后就会有几个特征的csv文件
  • 在这里插入图片描述
3.2人脸识别
# 摄像头实时人脸识别
#coding:utf-8
import os
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("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 = "./features_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.loc[i, :])):features_someone_arr.append(csv_rd.loc[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('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, 400)# 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 = './data/'# 最接近的人脸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[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 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 = "./data/KnownFacetrainset/"# 存储格式: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 = "./data/UnKnownFacetrainset"# 存储格式: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()
  • 第三步就会出现和第一步一样的结果了,哈哈哈,简直不错

4.小提示
  • 记得地址别搞错了,哈哈哈
  • 好像就没啥问题了
  • 全部具体代码下载人脸识别+数据采集+人脸特征提取(哈哈哈,绝决子)dlib库,shape全部代码-Actionscript文档类资源-CSDN文库

这篇关于人脸识别+数据采集+人脸特征提取(哈哈哈,绝决子)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/337302

相关文章

Python获取中国节假日数据记录入JSON文件

《Python获取中国节假日数据记录入JSON文件》项目系统内置的日历应用为了提升用户体验,特别设置了在调休日期显示“休”的UI图标功能,那么问题是这些调休数据从哪里来呢?我尝试一种更为智能的方法:P... 目录节假日数据获取存入jsON文件节假日数据读取封装完整代码项目系统内置的日历应用为了提升用户体验,

Java利用JSONPath操作JSON数据的技术指南

《Java利用JSONPath操作JSON数据的技术指南》JSONPath是一种强大的工具,用于查询和操作JSON数据,类似于SQL的语法,它为处理复杂的JSON数据结构提供了简单且高效... 目录1、简述2、什么是 jsONPath?3、Java 示例3.1 基本查询3.2 过滤查询3.3 递归搜索3.4

MySQL大表数据的分区与分库分表的实现

《MySQL大表数据的分区与分库分表的实现》数据库的分区和分库分表是两种常用的技术方案,本文主要介绍了MySQL大表数据的分区与分库分表的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有... 目录1. mysql大表数据的分区1.1 什么是分区?1.2 分区的类型1.3 分区的优点1.4 分

Mysql删除几亿条数据表中的部分数据的方法实现

《Mysql删除几亿条数据表中的部分数据的方法实现》在MySQL中删除一个大表中的数据时,需要特别注意操作的性能和对系统的影响,本文主要介绍了Mysql删除几亿条数据表中的部分数据的方法实现,具有一定... 目录1、需求2、方案1. 使用 DELETE 语句分批删除2. 使用 INPLACE ALTER T

Python Dash框架在数据可视化仪表板中的应用与实践记录

《PythonDash框架在数据可视化仪表板中的应用与实践记录》Python的PlotlyDash库提供了一种简便且强大的方式来构建和展示互动式数据仪表板,本篇文章将深入探讨如何使用Dash设计一... 目录python Dash框架在数据可视化仪表板中的应用与实践1. 什么是Plotly Dash?1.1

Redis 中的热点键和数据倾斜示例详解

《Redis中的热点键和数据倾斜示例详解》热点键是指在Redis中被频繁访问的特定键,这些键由于其高访问频率,可能导致Redis服务器的性能问题,尤其是在高并发场景下,本文给大家介绍Redis中的热... 目录Redis 中的热点键和数据倾斜热点键(Hot Key)定义特点应对策略示例数据倾斜(Data S

Python实现将MySQL中所有表的数据都导出为CSV文件并压缩

《Python实现将MySQL中所有表的数据都导出为CSV文件并压缩》这篇文章主要为大家详细介绍了如何使用Python将MySQL数据库中所有表的数据都导出为CSV文件到一个目录,并压缩为zip文件到... python将mysql数据库中所有表的数据都导出为CSV文件到一个目录,并压缩为zip文件到另一个

SpringBoot整合jasypt实现重要数据加密

《SpringBoot整合jasypt实现重要数据加密》Jasypt是一个专注于简化Java加密操作的开源工具,:本文主要介绍详细介绍了如何使用jasypt实现重要数据加密,感兴趣的小伙伴可... 目录jasypt简介 jasypt的优点SpringBoot使用jasypt创建mapper接口配置文件加密

使用Python高效获取网络数据的操作指南

《使用Python高效获取网络数据的操作指南》网络爬虫是一种自动化程序,用于访问和提取网站上的数据,Python是进行网络爬虫开发的理想语言,拥有丰富的库和工具,使得编写和维护爬虫变得简单高效,本文将... 目录网络爬虫的基本概念常用库介绍安装库Requests和BeautifulSoup爬虫开发发送请求解

Oracle存储过程里操作BLOB的字节数据的办法

《Oracle存储过程里操作BLOB的字节数据的办法》该篇文章介绍了如何在Oracle存储过程中操作BLOB的字节数据,作者研究了如何获取BLOB的字节长度、如何使用DBMS_LOB包进行BLOB操作... 目录一、缘由二、办法2.1 基本操作2.2 DBMS_LOB包2.3 字节级操作与RAW数据类型2.