您的位置:首页 > 理论基础 > 计算机网络

基于卷积神经网络实现的人脸识别

2018-04-01 21:33 597 查看
首先贴一下原文地址:http://tumumu.cn/2017/05/02/deep-learning-face/
以前在学习卷积神经网络的时候,发现了很多很有趣的demo,有一次发现了上面这个人脸识别的例子,不过当时还看不懂,经过一段时间之后决定试试能不能将上面的例子改一下,调以调参什么的,于是就有了这篇文章。本以为我的代码和原文没有什么太大的区别,应该不会出现什么错误,但是实际自己上手之后才会发现很多的问题。具体的程序安装,我这里就不再赘述了,大家可以参考原文,讲的很详细。下面我把我的代码贴出来。和原来的代码没有相差很多,就是改了一下中间的卷积层。自己实际操作还是学到了很多东西的。和原文相比,收集人脸和处理其他人脸的代码我都没有做太大的改变,只是去掉了原文代码中修改图片亮度和对比度的部分,所以我收集的图片都是一样的亮度和一样的对比度,这里就不贴这两部分的代码了。这里直接贴训练部分的代码和最后使用模型的代码。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 = './my_faces'
other_faces_path = './other_faces'
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)

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 = 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*8*64, 512])
bf = biasVariable([512])
drop3_flat = tf.reshape(drop3, [-1, 8*8*64])
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('./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:
saver.save(sess, './train_faces.model', global_step=n*num_batch+i)
sys.exit(0)
print('accuracy less 0.98, exited!')

cnnTrain()再加上最后使用模型的代码。import tensorflow as tf
import cv2
import numpy as np
import os
import random
import sys
from sklearn.model_selection import train_test_split
import dlib

my_faces_path = './my_faces'
other_faces_path = './other_faces'

#将得到的自己的图片和其他图片进行处理
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)

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 = 100
num_batch = (len(train_x)) // batch_size#计算总共多少轮

input = tf.placeholder(tf.float32,[None,size,size,3])
output = tf.placeholder(tf.float32,[None,2])#输出加两个,true or false
#这里注意的是tf.reshape不是np.reshape
images = tf.reshape(input,[-1,size,size,3])
#drop_out必须设置概率keep_prob,并且keep_prob也是一个占位符,跟输入是一样的,这里由于和原文不一样所以这里应该可以
#去除,因为我会在最后的全连接层设置drop_out而不是在每一层都设置drop_out
keep_prob_5 = tf.placeholder(tf.float32)
keep_prob_75 = tf.placeholder(tf.float32)

#下面开始进行卷积层的处理
#第一层卷积,首先输入的图片大小是64*64
def cnnlayer():
conv1 = tf.layers.conv2d(inputs=images,
filters=32,
kernel_size=[5,5],
strides=1,
padding='same',
activation=tf.nn.relu)#(64*64*6)
#第一层池化
pool1 = tf.layers.max_pooling2d(inputs=conv1,
pool_size=[2,2],
strides=2)#(32*32*6)

#第二层卷积
conv2 = tf.layers.conv2d(inputs=pool1,
filters=32,
kernel_size=[5,5],
strides=1,
padding='same',
activation=tf.nn.relu)#(32*32*6)

#第二层池化
pool2 = tf.layers.max_pooling2d(inputs=conv2,
pool_size=[2,2],
strides=2)#(16*16*6)

#第三层卷积
conv3 = tf.layers.conv2d(inputs=pool2,
filters=32,
kernel_size=[5,5],
strides=1,
padding='same',
activation=tf.nn.relu)#(变成16*16*6)
#第三层池化
pool2 = tf.layers.max_pooling2d(inputs=conv3,
pool_size=[2,2],
strides=2)#(8*8*6)

#第四层卷积
conv4 = tf.layers.conv2d(inputs=pool2,
filters=64,
kernel_size=[5,5],
strides=1,
padding='same',
activation=tf.nn.relu)#(变成8*8*6)
pool3 = tf.layers.max_pooling2d(inputs=conv4,
pool_size=[2,2],
strides=2)#(变成4*4*6)

#卷积网络在计算每一层的网络个数的时候要细心一些
#卷积层加的padding为same是不会改变卷积层的大小的
#要注意下一层的输入是上一层的输出
#平坦化
flat = tf.reshape(pool3,[-1,4*4*64])

#经过全连接层
dense = tf.layers.dense(inputs=flat,
units=4096,
activation=tf.nn.relu)

#drop_out,flat打错一次
drop_out = tf.layers.dropout(inputs=dense,rate=0.2)

#输出层
logits = tf.layers.dense(drop_out,units=2)
return logits

out = cnnlayer()
predict = tf.argmax(out,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={input: [image / 255.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()
总结:经过这一次的学习,对卷积神经网络有了更深的理解,在我修改代码的时候,虽然只是修改中间的卷积层,但还是出现了很多的问题,感觉自己不是写的代码而是写的bug。期间被卡住了很久,不过在Stack Overflow的一些大佬帮助下还是解决了问题(虽然我没有提问,但是上面之前的一些回答帮助了我很多)。总而言之,自己动手撸一遍代码还是比只是看看学到的多啊。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: