(记录)基于CNN的人脸识别实现
上学期自学了一点python,也了解了一些深度学习方面的知识,对人脸识别这个项目很感兴趣,于是自学了一些相关的知识,实现了基于CNN的人脸识别功能,所以整理在博客上作为记录。
关于CNN的基础知识可以看一下(https://blog.csdn.net/u012162613/article/details/43225445)这篇博客,想进一步理解的话推荐看一下周志华老师的机器学习(西瓜书),不过需要一些数学基础(后悔当时高数没认真研读,啃得巨慢)。
实现人脸识别的第一步是建立样本集,负样本的选择本人使用了celeba(一个香港中文大学提供的开放的人脸数据集,可以用百度云直接下载,很方便)。正样本(也就是需要识别的人脸)则需要自己想办法采样,这里我尝试了opencv和dlib的人脸检测分类器,感觉dlib夫人效果比较好,所以使用了dlib。为了模拟不同情况,这里参考了一位前辈的方法,为每张图设置了随机的亮度和对比度。
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
再对数据集进行大小调整后就可以使用CNN进行训练了,CNN主要构造是卷积层、池化层、全连接层和输出层,这里的结构是三层卷积、池化层,一层全连接层,一层输出层。
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 = biasVariable([2])
#out = tf.matmul(dropf, Wout) + bout
out = tf.add(tf.matmul(dropf, Wout), bout)
return out
训练一次用到的样本过多的话会导致训练时间太长(这里记得使用gpu加速),因此把数据分成了每块100张的图片块(batch_size),每次训练100张,当准确率达到理想数值时结束训练即可。
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):
# 每次取100(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!')
最后的工作是让机器识别出正样本(也就是本人的人脸),只需要打开摄像头使用dlib的分类器检测出人脸即可。
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()
类似功能的代码网上有很多,很容易就能找到,所以就只贴了部分代码。实际识别时,有时会出现识别失败的情况,估计应该是此时的光照、背景导致。所以要达到较高的准确率需要收集各种条件下的样本,或者对分类器检测出的人脸进一步处理后再进行识别。
完成人脸识别这个功能时参考了许多资料、许多别人成功实现的例子以及请教了一些老师。这一过程共感受到其实所谓的人脸识别等各种功能都可以抽象成是一个分类工作,所谓的深度学习等等做的也是这一工作。对于现在阶段我的水平来说我感觉很难去通过修改模型来提升性能,能做的工作大部分是对样本进行预处理来提高效果,所以想在这方面继续前进的话还需要继续学习。
虽然深度学习是个黑盒子,中间学习生成的数据很难通过数学来进行解释,但是还是要提高数学水平,从数学的层面把各种模型,各种方法弄清楚。