训练一个神经网络 能让她认得我

阅读原文

这段时间正在学习tensorflow的卷积神经网络部分,为了对卷积神经网络能够有一个更深的了解,自己动手实现一个例程是比较好的方式,所以就选了一个这样比较有点意思的项目。

项目的github地址:github 喜欢的话就给个Star吧。

想要她认得我,就需要给她一些我的照片,让她记住我的人脸特征,为了让她区分我和其他人,还需要给她一些其他人的照片做参照,所以就需要两组数据集来让她学习,如果想让她多认识几个人,那多给她几组图片集学习就可以了。下面就开始让我们来搭建这个能认识我的"她"。

运行环境

下面为软件的运行搭建系统环境。

系统: window或linux

软件: python 3.x 、 tensorflow

python支持库:

tensorflow:

pip install tensorflow      #cpu版本
pip install rensorflow-gpu  #gpu版本,需要cuda与cudnn的支持,不清楚的可以选择cpu版

numpy:

pip install numpy

opencv:

pip install opencv-python

dlib:

pip install dlib

获取本人图片集

获取本人照片的方式当然是拍照了,我们需要通过程序来给自己拍照,如果你自己有照片,也可以用那些现成的照片,但前提是你的照片足够多。这次用到的照片数是10000张,程序运行后,得坐在电脑面前不停得给自己的脸摆各种姿势,这样可以提高训练后识别自己的成功率,在程序中加入了随机改变对比度与亮度的模块,也是为了提高照片样本的多样性。

程序中使用的是dlib来识别人脸部分,也可以使用opencv来识别人脸,在实际使用过程中,dlib的识别效果比opencv的好,但opencv识别的速度会快很多,获取10000张人脸照片的情况下,dlib大约花费了1小时,而opencv的花费时间大概只有20分钟。opencv可能会识别一些奇怪的部分,所以综合考虑之后我使用了dlib来识别人脸。

get_my_faces.py

import cv2
import dlib
import os
import sys
import randomoutput_dir = './my_faces'
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)index = 1
while True:if (index <= 10000):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!')break

在这里我也给出一个opencv来识别人脸的代码示例:

import cv2
import os
import sys
import randomout_dir = './my_faces'
if not os.path.exists(out_dir):os.makedirs(out_dir)# 改变亮度与对比度
def relight(img, alpha=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]*alpha + bias)if tmp > 255:tmp = 255elif tmp < 0:tmp = 0img[j,i,c] = tmpreturn img# 获取分类器
haar = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')# 打开摄像头 参数为输入流,可以为摄像头或视频文件
camera = cv2.VideoCapture(0)n = 1
while 1:if (n <= 10000):print('It`s processing %s image.' % n)# 读帧success, img = camera.read()gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)faces = haar.detectMultiScale(gray_img, 1.3, 5)for f_x, f_y, f_w, f_h in faces:face = img[f_y:f_y+f_h, f_x:f_x+f_w]face = cv2.resize(face, (64,64))'''if n % 3 == 1:face = relight(face, 1, 50)elif n % 3 == 2:face = relight(face, 0.5, 0)'''face = relight(face, random.uniform(0.5, 1.5), random.randint(-50, 50))cv2.imshow('img', face)cv2.imwrite(out_dir+'/'+str(n)+'.jpg', face)n+=1key = cv2.waitKey(30) & 0xffif key == 27:breakelse:break

获取其他人脸图片集

需要收集一个其他人脸的图片集,只要不是自己的人脸都可以,可以在网上找到,这里我给出一个我用到的图片集:

网站地址:http://vis-www.cs.umass.edu/lfw/

图片集下载:http://vis-www.cs.umass.edu/lfw/lfw.tgz

先将下载的图片集,解压到项目目录下的input_img目录下,也可以自己指定目录(修改代码中的input_dir变量)

接下来使用dlib来批量识别图片中的人脸部分,并保存到指定目录下

set_other_people.py

# -*- codeing: utf-8 -*-
import sys
import os
import cv2
import dlibinput_dir = './input_img'
output_dir = './other_faces'
size = 64if not os.path.exists(output_dir):os.makedirs(output_dir)#使用dlib自带的frontal_face_detector作为我们的特征提取器
detector = dlib.get_frontal_face_detector()index = 1
for (path, dirnames, filenames) in os.walk(input_dir):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+'/'+str(index)+'.jpg', face)index += 1key = cv2.waitKey(30) & 0xffif key == 27:sys.exit(0)

这个项目用到的图片数是10000张左右,如果是自己下载的图片集,控制一下图片的数量避免数量不足,或图片过多带来的内存不够与运行缓慢。

训练模型

有了训练数据之后,通过cnn来训练数据,就可以让她记住我的人脸特征,学习怎么认识我了。

train_faces.py

import tensorflow as tf
import cv2
import numpy as np
import os
import random
import sys
from sklearn.model_selection import train_test_splitmy_faces_path = './my_faces'
other_faces_path = './other_faces'
size = 64imgs = []
labs = []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, rightdef 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.0print('train size:%s, test size:%s' % (len(train_x), len(test_x)))
# 图片块,每次取100张图片
batch_size = 100
num_batch = len(train_x) // batch_sizex = 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)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 outdef 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) % 100 == 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.98时保存并退出if acc > 0.98 and n > 2:saver.save(sess, './train_faces.model', global_step=n*num_batch+i)sys.exit(0)print('accuracy less 0.98, exited!')cnnTrain()

训练之后的数据会保存在当前目录下。

使用模型进行识别

最后就是让她认识我了,很简单,只要运行程序,让摄像头拍到我的脸,她就可以轻松地识别出是不是我了。

is_my_face.py

output = cnnLayer()
predict = tf.argmax(output, 1)  saver = tf.train.Saver()
sess = tf.Session()
saver.restore(sess, tf.train.latest_checkpoint('.'))  def is_my_face(image):  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 True  else:  return False  #使用dlib自带的frontal_face_detector作为我们的特征提取器
detector = dlib.get_frontal_face_detector()cam = cv2.VideoCapture(0)  while True:  _, img = cam.read()  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) & 0xff  if 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() 

转载于:https://www.cnblogs.com/mu---mu/p/FaceRecognition-tensorflow.html

写个神经网络,让她认得我`(๑•ᴗ•๑)(Tensorflow,opencv,dlib,cnn,人脸识别)相关推荐

  1. 基于神经网络的人脸识别(Tensorflow,opencv,dlib,cnn,)

    写个神经网络(Tensorflow,opencv,dlib,cnn,人脸识别) lvying 20180427 基于TensorFlow训练的人脸识别神经网络 训练一个神经网络 这段时间正在学习ten ...

  2. [Python人工智能] 十.Tensorflow+Opencv实现CNN自定义图像分类案例及与机器学习KNN图像分类算法对比

    从本专栏开始,作者正式开始研究Python深度学习.神经网络及人工智能相关知识.前一篇详细讲解了gensim词向量Word2Vec安装.基础用法,并实现<庆余年>中文短文本相似度计算及多个 ...

  3. 基于Tensorflow + Opencv 实现CNN自定义图像分类

    摘要:本篇文章主要通过Tensorflow+Opencv实现CNN自定义图像分类案例,它能解决我们现实论文或实践中的图像分类问题,并与机器学习的图像分类算法进行对比实验. 本文分享自华为云社区< ...

  4. gpu训练cnn人脸识别准确率_opencv+mtcnn+facenet+python+tensorflow 实现实时人脸识别

    opencv+mtcnn+facenet+python+tensorflow 实现实时人脸识别 Abstract:本文记录了在学习深度学习过程中,使用opencv+mtcnn+facenet+pyth ...

  5. 用python实现人脸识别输出画像_这个是利用OpenCV TensorFlow来实现图片人脸识别

    安装 dlib dlib 是一个基于 C++ 编写的扩展库,包含有许多常用的机器学习算法以及图像处理函数. 并且还支持大量的数值计算,如矩阵.大整数随机运算等. 但是在编译安装 dlib 之前我们还需 ...

  6. TensorFlow框架做实时人脸识别小项目

    人脸识别是深度学习最有价值也是最成熟的的应用之一.在研究环境下,人脸识别已经赶上甚至超过了人工识别的精度.一般来说,一个完整的人脸识别项目会包括两大部分:人脸检测与人脸识别.下面就我近期自己练习写的一 ...

  7. 人工智能python3+tensorflow人脸识别_机器学习tensorflow object detection 实现人脸识别...

    object detection是Tensorflow很常用的api,功能强大,很有想象空间,人脸识别,花草识别,物品识别等.下面是我做实验的全过程,使用自己收集的胡歌图片,实现人脸识别,找出胡歌. ...

  8. 数字识别实例两种实现方式(tensorflow2.x):1.调用高级API 2.手写简单神经网络 3.手写深度神经网络(DNN)

    MNIST手写数字数据库的训练集为60,000个示例,而测试集为10,000个示例. 一共4个文件,训练集.训练集标签.测试集.测试集标签,这些数据直接可以用mnist = tf.keras.data ...

  9. tensorflow精进之路(二十六)——人脸识别(上)(MTCNN原理)

    1.概述 换了个固态硬盘,本想装最新的系统mint 19,谁知道却是个坑,NVIDIA驱动和CUDA工具老是装不上去,各种问题,折腾了几天,还是用回了原来的系统.不过,这次软件改了一下,使用了pyth ...

最新文章

  1. 国内四大搜索站长工具
  2. java access 分页查询语句,简单又高效的Access分页语句
  3. asp按钮跳转页面代码_重磅更新!全新Web编辑页面、编辑规则快速跳转、状态栏变色、富文本再次升级!...
  4. 外星人台式电脑_执掌游戏世界 外星人ALIENWARE m15丨17.9mm机身轻悍降临【电脑组装】公众号分享台式机笔记本电脑 京东商城特惠通道...
  5. 微信小程序消息推送自有服务器无法接收到信息,消息推送服务器配置次数用完的解决方式。
  6. (57)FPGA条件选择无优先级(case)
  7. 云卓遥控器+DIY高清摄像机的方案(完美接入原系统)
  8. spring boot全局统一异常处理
  9. 【Android安全】手机Root、刷机、救砖常用命令
  10. 2020年中国研究生数学建模竞赛E题
  11. 11.4王者荣耀服务器维护中,英雄战迹11号更新维护公告 删档最后一更
  12. 智能语音小夜灯 开灯关灯只需要说一声!#懒人必备神器
  13. 谨慎处理单片机中断,中断等价于比主程序优先级更高的线程
  14. 关于线程中断thread interrupt
  15. 利用python进行png图像的读写操作
  16. 【C语言初学必看】猜数字游戏背后的知识
  17. c语言中十六进制乘以16啥意思,C语言16进制中16怎么表示?
  18. 实战 webpack 4 配置解析四
  19. 机器学习系列笔记一:Introduction
  20. gentoo命令行刻录

热门文章

  1. POJ 1062 昂贵的聘礼【经典的最短路问题】
  2. 《信息化项目文档模板十一——系统运维流程工作流程模板》
  3. 如何打造百万爆款短视频?普通人如何通过短视频赚钱?3分钟学会
  4. 更新后的微信新功能,你知道吗?
  5. 干货 | SQL 进阶技巧
  6. python实现hbase增删改查
  7. xmind 8系列便携版:关联.xmind文件的打开方式后,打开文件会在当前文件夹下产生configuration等子目录的问题解决办法
  8. google官方提供的颜色表。
  9. 计算机英语格式怎么写,26个英文字母,正确的书写格式,孩子真的会吗?
  10. python读取word内容复制粘贴_如何复制word文档的内容?