-------让系统认识我-------
-------人脸识别系统-------
---VERSION2:基于tensorflow_cnn来做模型
---背景:
上一篇我的github:zhenghaozhang(https://github.com/zhenghaozhang123/dlib_face_recognize)讲了利用dlib来进行人脸识别的例子,列举了三个缺点。
此处模型解决了上一篇讲到的两个缺点:
1.判定是否同一个人的阈值难以确定。
2.模型适合小型人脸数据库,一旦人脸数据库人数过多,此处的阈值更加难以确定。
---优点:
1.不再利用dist距离法,也就不再需要去定义阈值。因为上一篇我写到,阈值的值非常难定,特别是当人脸数据库人数多时,dist这个值是不稳定,甚至没办法确定的。 因此我们利用cnn的模型,将思路从两张图片的dist距离转换为“是非”问题,即二分类问题。(1.是我数据库的人。0.不是我数据库的人)。从而解决阈值选择的困难。
2.模型可以是多样本模型,解决了DLIB存在的小样本模型的局限。上一篇我讲到,当人脸数量一旦增加时,dist将是不稳定的。而用tensorflow的cnn模型,我们可以将 我们需要存进我们人脸数据库的人脸存进数据库,并将其定义为Label 1.训练时将不属于人脸数据库的数据定义为LABEL 0。因此成功将问题转换为二分类问题。相信 二分类问题大家很熟悉了。
---缺点:
当我们完成训练好的模型之后,一旦我们要往人脸数据库中增加新成员,则需要重新去跑模型(因为模型需要去记住新的成员,所以模型需要重新训练)。我们知道在现实 中,训练一个好的模型参数出来是需要花费大量时间的,如果一旦增加新成员,便重新训练模型,这个成本是相当高的,也不符合实际。 (此处的缺点解决方案,我将在下一篇进行讲解)
此处为版本2.通过tensorflow_cnn,将定阈值问题转换为二分类问题。
此处案例为了简便讲解和与上一篇的案例做对比,依旧以识别本人项目为主。
现在开始我们的代码学习吧。
get_my_faces.py -----通过电脑摄像头实现对自己人脸的抓取,并储存在个人人脸数据库中,以备后面进行识别。
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 30 15:22:58 2018
@author: MR.ZHENG
"""
import cv2
import dlib
import os
import sys
import random
output_dir = "D:/Git_code/tensorflow_dlib_face_recognize/my_face/"
size = 64
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 = 255
elif tmp < 0:
tmp = 0
img[j,i,c] = tmp
return 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 0
y1 = d.bottom() if d.bottom() > 0 else 0
x2 = d.left() if d.left() > 0 else 0
y2 = d.right() if d.right() > 0 else 0
face = 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 += 1
key = cv2.waitKey(30) & 0xff
if key == 27:
break
else:
print('Finished!')
break
get_other_people.py -----提取他人照片存放在另一个数据库中,这个数据库是为了训练网络时候,与本人人脸数据库做比对的数据。
import sys
import os
import cv2
import dlib
input_dir = "D:/Git_code/tensorflow_dlib_face_recognize/dataset/"#数据集,除了本人之外的数据集,此处取LFW数据集
output_dir = "D:/Git_code/tensorflow_dlib_face_recognize/dataset1/"#输出地址
size = 64
if 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 0
y1 = d.bottom() if d.bottom() > 0 else 0
x2 = d.left() if d.left() > 0 else 0
y2 = 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 += 1
key = cv2.waitKey(30) & 0xff
if key == 27:
sys.exit(0)
完成上面两个步骤之后,将存在两个数据库,一个是我本人的数据库,一个是他人的数据库。这两个数据库就是我们的二分类问题。我们需要网络去完成的任务就是: 告诉网络,照片A是来自哪个数据库的。比如告诉网络:照片A 是我的数据库的,它的标签为1. 照片B 不是我的数据库的,它的标签为0.我们需要通过不断训练网络 在不过拟合的情况下,让网络熟悉我告诉它要做的事情。
train.py -----这个就是我们的网络,也是整个环节的重点,但是其实网络并不难,只需要补补基础卷积神经网络就会用。
import tensorflow as tf
import cv2
import numpy as np
import os
import random
import sys
from sklearn.model_selection import train_test_split
my_faces_path = "D:/Git_code/tensorflow_dlib_face_recognize/my_face"
other_faces_path = "D:/Git_code/tensorflow_dlib_face_recognize/dataset1/"
size = 64 #照片人脸的修改尺寸
imgs = []
labs = []
def getPaddingSize(img):
h, w, _ = img.shape
top, bottom, left, right = (0,0,0,0)
longest = max(h, w)
if w < longest:
tmp = longest - w
# //表示整除符号
left = tmp // 2
right = tmp - left
elif h < longest:
tmp = longest - h
top = tmp // 2
bottom = tmp - top
else:
pass
return top, bottom, left, right
def readData(path , h=size, w=size):
for filename in os.listdir(path):
if filename.endswith('.jpg'):
filename = path + '/' + filename
img = cv2.imread(filename)#读取成BRG格式
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)
# 将图片数据与标签转换成数组3
imgs = np.array(imgs)
#将问题转为二分类问题。[0,1] or [1,0]
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 = 100
num_batch = len(train_x) // batch_size
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)
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) + bout
out = tf.add(tf.matmul(dropf, Wout), bout)
return out
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("D:/Git_code/tensorflow_dlib_face_recognize/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, 'D:/Git_code/tensorflow_dlib_face_recognize/tmp/train_faces.model', global_step=n*num_batch+i)
sys.exit(0)
cnnTrain()
recognize_me -----加载我们已经训练好的模型,并将模型利用摄像头来识别是否本人。
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 0
y1 = d.bottom() if d.bottom() > 0 else 0
x2 = d.left() if d.left() > 0 else 0
y2 = d.right() if d.right() > 0 else 0
face = 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) & 0xff
if key == 27:
sys.exit(0)
sess.close()
神经网络中参数的选择:
我建议使用已经他人选择好的网络,免去一些步骤,一般已经落实下去的网络参数都是具备通用性的。当然除了矩阵是需要修改的。好比当你的图片尺寸进行修改后,你的 W 值 的shape 是需要进行修改的。当然如果你也可以自己来定义网络参数。
文章取自我的github:zhenghaozhang123 .https://github.com/zhenghaozhang123/tensorflow_cnn_face_recognize
备注:这个模型是本人做人脸识别系统项目时候的个人见解,如果存在知识点上的误导,希望大家可以email来联系我:[email protected]