python:卷积网络实现人脸识别,dlib (也可以用openCV)

2024-04-09 06:28

本文主要是介绍python:卷积网络实现人脸识别,dlib (也可以用openCV),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一.项目简介

1.数据

数据下载链接人脸识别数据集_免费高速下载|百度网盘-分享无限制

数据集:总共数据集由两部分组成:他人脸图片集及我自己的部分图片
自己图片目录:face_recog/my_faces
他人图片目录:face_recog/other_faces
我的测试图片目录:face_recog/test_faces

2.人脸识别

获取数据后,第一件事就对对图片进行处理,即人脸识别,把人脸的范围确定下来,人脸识别有很多方法,这里使用的是 dlib 来识别人脸部分,当然也可以使用 opencv 来识别人脸,在实际使用过程中,dlib 的识别效果比 opencv 的好一些
识别处理后的图片存放路径为:my_faces(存放预处理我的图片,里面还复制一些图片),other_faces(存放预处理别人图片)

3.建立模型,训练数据

这里使用卷积神经网络来建立模型,用了 3 个卷积层(采用了池化、dropout 等技术),一个全连接层,分类层、输出层。

4.性能评估

5. 用测试数据,验证模型

下面开始代码实现啦

二.数据准备

导入模块

import sys
import os
import cv2
import dlib
import matplotlib
import time
start=time.time()

1.获取数据

# 1.定义输入、输出目录,文件解压到当前目录,my_faces目录下,output_dir_myself 为检测以后我的的头像
input_dir_myself = 'face_recog/my_faces'
output_dir_myself = 'my_faces'
size = 64*# 2.判断输出目录是否存在,不存在,则创建
if not os.path.exists(output_dir_myself):os.makedirs(output_dir_myself)# 3.利用 dlib 的人脸特征提取器,使用 dlib 自带的 frontal_face_detector 作为我们的特征提取器
detector = dlib.get_frontal_face_detector()

2.预处理数据

# 接下来使用 dlib 来批量识别图片中的人脸部分,并对原图像进行预处理,并保存到指定目录下。
#1.预处理我的头像
index = 1
for (path, dirnames, filenames) in os.walk(input_dir_myself):for filename in filenames:if filename.endswith('.jpg'):print('Being processed picture %s' % index)img_path = path+'/'+filename# 从文件读取图片img = cv2.imread(img_path)# 转为灰度图片gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# 使用 detector 进行人脸检测 dets 为返回的结果dets = detector(gray_img, 1)#使用 enumerate 函数遍历序列中的元素以及它们的下标#下标 i 即为人脸序号#left:人脸左边距离图片左边界的距离 ;right:人脸右边距离图片左边界的距离#top:人脸上边距离图片上边界的距离 ;bottom:人脸下边距离图片上边界的距离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 0# img[y:y+h,x:x+w]face = img[x1:y1,x2:y2]# 调整图片的尺寸face = cv2.resize(face, (size,size))cv2.imshow('image',face)# 保存图片cv2.imwrite(output_dir_myself + '/' + str(index) + '.jpg', face)index += 1# 不断刷新图像,频率时间为 30mskey = cv2.waitKey(30) & 0xffif key == 27:sys.exit(0)# 2.用同样方法预处理别人的头像(我只选用别人部分头像)
# 定义输入、输出目录,文件解压到当前目录,other_faces目录下
input_dir_other = 'face_recog/other_faces'
output_dir_other = 'other_faces'
size = 64
# 判断输出目录是否存在,不存在,则创建
if not os.path.exists(output_dir_other):os.makedirs(output_dir_other)
#使用 dlib 自带的 frontal_face_detector 作为我们的特征提取器
detector = dlib.get_frontal_face_detector()
# 预处理别人的头像
index = 1
for (path, dirnames, filenames) in os.walk(input_dir_other):for filename in filenames:if filename.endswith('.jpg'):print('Being processed picture %s' % index)img_path = path+'/'+filename# 从文件读取图片img = cv2.imread(img_path)# 转为灰度图片gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# 使用 detector 进行人脸检测 dets 为返回的结果dets = detector(gray_img, 1)#使用 enumerate 函数遍历序列中的元素以及它们的下标#下标 i 即为人脸序号#left:人脸左边距离图片左边界的距离 ;right:人脸右边距离图片左边界的距离#top:人脸上边距离图片上边界的距离 ;bottom:人脸下边距离图片上边界的距离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 0# img[y:y+h,x:x+w]face = img[x1:y1,x2:y2]# 调整图片的尺寸face = cv2.resize(face, (size,size))cv2.imshow('image',face)# 保存图片cv2.imwrite(output_dir_other + '/' + str(index) + '.jpg', face)index += 1# 不断刷新图像,频率时间为 30mskey = cv2.waitKey(30) & 0xffif key == 27:sys.exit(0)

三.训练模型

1.导入需要的库

import tensorflow as tf
import cv2
import numpy as np
import os
import random
import sys
from sklearn.model_selection import train_test_split

2.定义预处理后图片(我的和别人的)所在目录

my_faces_path = 'my_faces'
other_faces_path = 'other_faces'
size = 64

3.调整或规范图片大小

imgs = []
labs = []
#重新创建图形变量
tf.reset_default_graph()
#获取需要填充图片的大小
def getPaddingSize(img):h, w, _ = img.shapetop, bottom, left, right = (0, 0, 0, 0)longest = max(h, w)if w < longest:tmp = longest - w# //表示整除符号left = tmp // 2right = tmp - leftelif h < longest:tmp = longest - htop = tmp // 2bottom = tmp - topelse:passreturn top, bottom, left, right

4.读取测试图片

def readData(path , h=size, w=size):for filename in os.listdir(path):if filename.endswith('.jpg'):filename = path + '/' + filenameimg = cv2.imread(filename)top,bottom,left,right = getPaddingSize(img)# 将图片放大, 扩充图片边缘部分img = cv2.copyMakeBorder(img, top, bottom, left, right,cv2.BORDER_CONSTANT, value=[0,0,0])img = cv2.resize(img, (h, w))imgs.append(img)labs.append(path)
readData(my_faces_path)
readData(other_faces_path)
# 将图片数据与标签转换成数组
imgs = np.array(imgs)
labs = np.array([[0,1] if lab == my_faces_path else [1,0] for lab in labs])
# 随机划分测试集与训练集
train_x,test_x,train_y,test_y = train_test_split(imgs, labs, test_size=0.05,
random_state=random.randint(0,100))
# 参数:图片数据的总数,图片的高、宽、通道
train_x = train_x.reshape(train_x.shape[0], size, size, 3)
test_x = test_x.reshape(test_x.shape[0], size, size, 3)
# 将数据转换成小于 1 的数
train_x = train_x.astype('float32')/255.0
test_x = test_x.astype('float32')/255.0
print('train size:%s, test size:%s' % (len(train_x), len(test_x)))
# 图片块,每次取 100 张图片
batch_size = 20
num_batch = len(train_x) // batch_size

5.定义变量及神经网络层-

x = tf.placeholder(tf.float32, [None, size, size, 3])
y_ = tf.placeholder(tf.float32, [None, 2])
keep_prob_5 = tf.placeholder(tf.float32)
keep_prob_75 = tf.placeholder(tf.float32)
def weightVariable(shape):init = tf.random_normal(shape, stddev=0.01)return tf.Variable(init)
def biasVariable(shape):init = tf.random_normal(shape)return tf.Variable(init)
def conv2d(x, W):return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME')
def maxPool(x):return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')
def dropout(x, keep):return tf.nn.dropout(x, keep)

6.定义卷积神经网络框架

def cnnLayer():# 第一层W1 = weightVariable([3, 3, 3, 32])  # 卷积核大小(3,3), 输入通道(3), 输出通道(32)b1 = biasVariable([32])# 卷积conv1 = tf.nn.relu(conv2d(x, W1) + b1)# 池化pool1 = maxPool(conv1)# 减少过拟合,随机让某些权重不更新drop1 = dropout(pool1, keep_prob_5)# 第二层W2 = weightVariable([3, 3, 32, 64])b2 = biasVariable([64])conv2 = tf.nn.relu(conv2d(drop1, W2) + b2)pool2 = maxPool(conv2)drop2 = dropout(pool2, keep_prob_5)# 第三层W3 = weightVariable([3, 3, 64, 64])b3 = biasVariable([64])conv3 = tf.nn.relu(conv2d(drop2, W3) + b3)pool3 = maxPool(conv3)drop3 = dropout(pool3, keep_prob_5)# 全连接层Wf = weightVariable([8 * 16 * 32, 512])bf = biasVariable([512])drop3_flat = tf.reshape(drop3, [-1, 8 * 16 * 32])dense = tf.nn.relu(tf.matmul(drop3_flat, Wf) + bf)dropf = dropout(dense, keep_prob_75)# 输出层Wout = weightVariable([512, 2])bout = weightVariable([2])# out = tf.matmul(dropf, Wout) + boutout = tf.add(tf.matmul(dropf, Wout), bout)return out

7.训练模型

def cnnTrain():out = cnnLayer()cross_entropy =tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=out, labels=y_))train_step = tf.train.AdamOptimizer(0.01).minimize(cross_entropy)# 比较标签是否相等,再求的所有数的平均值,tf.cast(强制转换类型)accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(out, 1), tf.argmax(y_,1)), tf.float32))# 将 loss 与 accuracy 保存以供 tensorboard 使用tf.summary.scalar('loss', cross_entropy)tf.summary.scalar('accuracy', accuracy)merged_summary_op = tf.summary.merge_all()# 数据保存器的初始化saver = tf.train.Saver()with tf.Session() as sess:sess.run(tf.global_variables_initializer())summary_writer = tf.summary.FileWriter('./tmp',graph=tf.get_default_graph())for n in range(10):# 每次取 128(batch_size)张图片for i in range(num_batch):batch_x = train_x[i * batch_size: (i + 1) * batch_size]batch_y = train_y[i * batch_size: (i + 1) * batch_size]# 开始训练数据,同时训练三个变量,返回三个数据_, loss, summary = sess.run([train_step, cross_entropy,merged_summary_op],feed_dict={x: batch_x, y_: batch_y,keep_prob_5: 0.5, keep_prob_75: 0.75})summary_writer.add_summary(summary, n * num_batch + i)# 打印损失print(n * num_batch + i, loss)if (n * num_batch + i) % 40 == 0:# 获取测试数据的准确率acc = accuracy.eval({x: test_x, y_: test_y, keep_prob_5: 1.0,keep_prob_75: 1.0})print(n * num_batch + i, acc)# 由于数据不多,这里设为准确率大于 0.80 时保存并退出if acc > 0.8 and n > 2:# saver.save(sess,'./train_face_model/train_faces.model', global_step = n * num_batch + i)saver.save(sess,'./train_face_model/train_faces.model')# sys.exit(0)# print('accuracy less 0.80, exited!')
cnnTrain()

四.测试模型

input_dir='face_recog/test_faces'
index=1
output = cnnLayer()
predict = tf.argmax(output, 1)
#先加载 meta graph 并恢复权重变量
saver = tf.train.import_meta_graph('./train_face_model/train_faces.model.meta')
sess = tf.Session()
saver.restore(sess, tf.train.latest_checkpoint('./train_face_model/'))
#saver.restore(sess,tf.train.latest_checkpoint('./my_test_model/'))
def is_my_face(image):sess.run(tf.global_variables_initializer())res = sess.run(predict, feed_dict={x: [image/255.0], keep_prob_5:1.0,keep_prob_75: 1.0})if res[0] == 1:return Trueelse:return False
#使用 dlib 自带的 frontal_face_detector 作为我们的特征提取器
detector = dlib.get_frontal_face_detector()
#cam = cv2.VideoCapture(0)
#while True:#_, img = cam.read()
for (path, dirnames, filenames) in os.walk(input_dir):for filename in filenames:if filename.endswith('.jpg'):print('Being processed picture %s' % index)index += 1img_path = path + '/' + filename# 从文件读取图片img = cv2.imread(img_path)gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)dets = detector(gray_image, 1)if not len(dets):print('Can`t get face.')cv2.imshow('img', img)key = cv2.waitKey(30) & 0xffif key == 27:sys.exit(0)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 = cv2.resize(face, (size, size))print('Is this my face? %s' % is_my_face(face))cv2.rectangle(img, (x2, x1), (y2, y1), (255, 0, 0), 3)cv2.imshow('image', img)key = cv2.waitKey(30) & 0xffif key == 27:sys.exit(0)
sess.close()

成果展示

引用块内容

总结

由于图片数量比较少,最终结果不是很理想,但是整个流程的逻辑是很透彻的,本人电脑比较渣,跑的时候比较慢。样本图片越多,最终的结果也越准确。

这篇关于python:卷积网络实现人脸识别,dlib (也可以用openCV)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

Python使用Matplotlib绘制3D曲面图详解

《Python使用Matplotlib绘制3D曲面图详解》:本文主要介绍Python使用Matplotlib绘制3D曲面图,在Python中,使用Matplotlib库绘制3D曲面图可以通过mpl... 目录准备工作绘制简单的 3D 曲面图绘制 3D 曲面图添加线框和透明度控制图形视角Matplotlib

一文教你Python如何快速精准抓取网页数据

《一文教你Python如何快速精准抓取网页数据》这篇文章主要为大家详细介绍了如何利用Python实现快速精准抓取网页数据,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以了解下... 目录1. 准备工作2. 基础爬虫实现3. 高级功能扩展3.1 抓取文章详情3.2 保存数据到文件4. 完整示例

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

基于Python打造一个智能单词管理神器

《基于Python打造一个智能单词管理神器》这篇文章主要为大家详细介绍了如何使用Python打造一个智能单词管理神器,从查询到导出的一站式解决,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 项目概述:为什么需要这个工具2. 环境搭建与快速入门2.1 环境要求2.2 首次运行配置3. 核心功能使用指

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

利用Python打造一个Excel记账模板

《利用Python打造一个Excel记账模板》这篇文章主要为大家详细介绍了如何使用Python打造一个超实用的Excel记账模板,可以帮助大家高效管理财务,迈向财富自由之路,感兴趣的小伙伴快跟随小编一... 目录设置预算百分比超支标红预警记账模板功能介绍基础记账预算管理可视化分析摸鱼时间理财法碎片时间利用财

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

Python中的Walrus运算符分析示例详解

《Python中的Walrus运算符分析示例详解》Python中的Walrus运算符(:=)是Python3.8引入的一个新特性,允许在表达式中同时赋值和返回值,它的核心作用是减少重复计算,提升代码简... 目录1. 在循环中避免重复计算2. 在条件判断中同时赋值变量3. 在列表推导式或字典推导式中简化逻辑