人脸识别--训练一个认识我的神经网络

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

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

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

运行环境

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

系统: window或linux

软件: python 3.x 、 tensorflow

python支持库:

tensorflow:

 
  1. pip install tensorflow #cpu版本

  2. 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

 
  1. import cv2

  2. import dlib

  3. import os

  4. import sys

  5. import random

  6.  
  7. output_dir = './my_faces'

  8. size = 64

  9.  
  10. if not os.path.exists(output_dir):

  11. os.makedirs(output_dir)

  12.  
  13. # 改变图片的亮度与对比度

  14. def relight(img, light=1, bias=0):

  15. w = img.shape[1]

  16. h = img.shape[0]

  17. #image = []

  18. for i in range(0,w):

  19. for j in range(0,h):

  20. for c in range(3):

  21. tmp = int(img[j,i,c]*light + bias)

  22. if tmp > 255:

  23. tmp = 255

  24. elif tmp < 0:

  25. tmp = 0

  26. img[j,i,c] = tmp

  27. return img

  28.  
  29. #使用dlib自带的frontal_face_detector作为我们的特征提取器

  30. detector = dlib.get_frontal_face_detector()

  31. # 打开摄像头 参数为输入流,可以为摄像头或视频文件

  32. camera = cv2.VideoCapture(0)

  33.  
  34. index = 1

  35. while True:

  36. if (index <= 10000):

  37. print('Being processed picture %s' % index)

  38. # 从摄像头读取照片

  39. success, img = camera.read()

  40. # 转为灰度图片

  41. gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

  42. # 使用detector进行人脸检测

  43. dets = detector(gray_img, 1)

  44.  
  45. for i, d in enumerate(dets):

  46. x1 = d.top() if d.top() > 0 else 0

  47. y1 = d.bottom() if d.bottom() > 0 else 0

  48. x2 = d.left() if d.left() > 0 else 0

  49. y2 = d.right() if d.right() > 0 else 0

  50.  
  51. face = img[x1:y1,x2:y2]

  52. # 调整图片的对比度与亮度, 对比度与亮度值都取随机数,这样能增加样本的多样性

  53. face = relight(face, random.uniform(0.5, 1.5), random.randint(-50, 50))

  54.  
  55. face = cv2.resize(face, (size,size))

  56.  
  57. cv2.imshow('image', face)

  58.  
  59. cv2.imwrite(output_dir+'/'+str(index)+'.jpg', face)

  60.  
  61. index += 1

  62. key = cv2.waitKey(30) & 0xff

  63. if key == 27:

  64. break

  65. else:

  66. print('Finished!')

  67. break

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

 
  1. import cv2

  2. import os

  3. import sys

  4. import random

  5.  
  6. out_dir = './my_faces'

  7. if not os.path.exists(out_dir):

  8. os.makedirs(out_dir)

  9.  
  10.  
  11. # 改变亮度与对比度

  12. def relight(img, alpha=1, bias=0):

  13. w = img.shape[1]

  14. h = img.shape[0]

  15. #image = []

  16. for i in range(0,w):

  17. for j in range(0,h):

  18. for c in range(3):

  19. tmp = int(img[j,i,c]*alpha + bias)

  20. if tmp > 255:

  21. tmp = 255

  22. elif tmp < 0:

  23. tmp = 0

  24. img[j,i,c] = tmp

  25. return img

  26.  
  27.  
  28. # 获取分类器

  29. haar = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

  30.  
  31. # 打开摄像头 参数为输入流,可以为摄像头或视频文件

  32. camera = cv2.VideoCapture(0)

  33.  
  34. n = 1

  35. while 1:

  36. if (n <= 10000):

  37. print('It`s processing %s image.' % n)

  38. # 读帧

  39. success, img = camera.read()

  40.  
  41. gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

  42. faces = haar.detectMultiScale(gray_img, 1.3, 5)

  43. for f_x, f_y, f_w, f_h in faces:

  44. face = img[f_y:f_y+f_h, f_x:f_x+f_w]

  45. face = cv2.resize(face, (64,64))

  46. '''

  47. if n % 3 == 1:

  48. face = relight(face, 1, 50)

  49. elif n % 3 == 2:

  50. face = relight(face, 0.5, 0)

  51. '''

  52. face = relight(face, random.uniform(0.5, 1.5), random.randint(-50, 50))

  53. cv2.imshow('img', face)

  54. cv2.imwrite(out_dir+'/'+str(n)+'.jpg', face)

  55. n+=1

  56. key = cv2.waitKey(30) & 0xff

  57. if key == 27:

  58. break

  59. else:

  60. 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

 
  1. # -*- codeing: utf-8 -*-

  2. import sys

  3. import os

  4. import cv2

  5. import dlib

  6.  
  7. input_dir = './input_img'

  8. output_dir = './other_faces'

  9. size = 64

  10.  
  11. if not os.path.exists(output_dir):

  12. os.makedirs(output_dir)

  13.  
  14. #使用dlib自带的frontal_face_detector作为我们的特征提取器

  15. detector = dlib.get_frontal_face_detector()

  16.  
  17. index = 1

  18. for (path, dirnames, filenames) in os.walk(input_dir):

  19. for filename in filenames:

  20. if filename.endswith('.jpg'):

  21. print('Being processed picture %s' % index)

  22. img_path = path+'/'+filename

  23. # 从文件读取图片

  24. img = cv2.imread(img_path)

  25. # 转为灰度图片

  26. gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

  27. # 使用detector进行人脸检测 dets为返回的结果

  28. dets = detector(gray_img, 1)

  29.  
  30. #使用enumerate 函数遍历序列中的元素以及它们的下标

  31. #下标i即为人脸序号

  32. #left:人脸左边距离图片左边界的距离 ;right:人脸右边距离图片左边界的距离

  33. #top:人脸上边距离图片上边界的距离 ;bottom:人脸下边距离图片上边界的距离

  34. for i, d in enumerate(dets):

  35. x1 = d.top() if d.top() > 0 else 0

  36. y1 = d.bottom() if d.bottom() > 0 else 0

  37. x2 = d.left() if d.left() > 0 else 0

  38. y2 = d.right() if d.right() > 0 else 0

  39. # img[y:y+h,x:x+w]

  40. face = img[x1:y1,x2:y2]

  41. # 调整图片的尺寸

  42. face = cv2.resize(face, (size,size))

  43. cv2.imshow('image',face)

  44. # 保存图片

  45. cv2.imwrite(output_dir+'/'+str(index)+'.jpg', face)

  46. index += 1

  47.  
  48. key = cv2.waitKey(30) & 0xff

  49. if key == 27:

  50. sys.exit(0)

 

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

训练模型

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

train_faces.py

 
  1. import tensorflow as tf

  2. import cv2

  3. import numpy as np

  4. import os

  5. import random

  6. import sys

  7. from sklearn.model_selection import train_test_split

  8.  
  9. my_faces_path = './my_faces'

  10. other_faces_path = './other_faces'

  11. size = 64

  12.  
  13. imgs = []

  14. labs = []

  15.  
  16. def getPaddingSize(img):

  17. h, w, _ = img.shape

  18. top, bottom, left, right = (0,0,0,0)

  19. longest = max(h, w)

  20.  
  21. if w < longest:

  22. tmp = longest - w

  23. # //表示整除符号

  24. left = tmp // 2

  25. right = tmp - left

  26. elif h < longest:

  27. tmp = longest - h

  28. top = tmp // 2

  29. bottom = tmp - top

  30. else:

  31. pass

  32. return top, bottom, left, right

  33.  
  34. def readData(path , h=size, w=size):

  35. for filename in os.listdir(path):

  36. if filename.endswith('.jpg'):

  37. filename = path + '/' + filename

  38.  
  39. img = cv2.imread(filename)

  40.  
  41. top,bottom,left,right = getPaddingSize(img)

  42. # 将图片放大, 扩充图片边缘部分

  43. img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=[0,0,0])

  44. img = cv2.resize(img, (h, w))

  45.  
  46. imgs.append(img)

  47. labs.append(path)

  48.  
  49. readData(my_faces_path)

  50. readData(other_faces_path)

  51. # 将图片数据与标签转换成数组

  52. imgs = np.array(imgs)

  53. labs = np.array([[0,1] if lab == my_faces_path else [1,0] for lab in labs])

  54. # 随机划分测试集与训练集

  55. train_x,test_x,train_y,test_y = train_test_split(imgs, labs, test_size=0.05, random_state=random.randint(0,100))

  56. # 参数:图片数据的总数,图片的高、宽、通道

  57. train_x = train_x.reshape(train_x.shape[0], size, size, 3)

  58. test_x = test_x.reshape(test_x.shape[0], size, size, 3)

  59. # 将数据转换成小于1的数

  60. train_x = train_x.astype('float32')/255.0

  61. test_x = test_x.astype('float32')/255.0

  62.  
  63. print('train size:%s, test size:%s' % (len(train_x), len(test_x)))

  64. # 图片块,每次取100张图片

  65. batch_size = 100

  66. num_batch = len(train_x) // batch_size

  67.  
  68. x = tf.placeholder(tf.float32, [None, size, size, 3])

  69. y_ = tf.placeholder(tf.float32, [None, 2])

  70.  
  71. keep_prob_5 = tf.placeholder(tf.float32)

  72. keep_prob_75 = tf.placeholder(tf.float32)

  73.  
  74. def weightVariable(shape):

  75. init = tf.random_normal(shape, stddev=0.01)

  76. return tf.Variable(init)

  77.  
  78. def biasVariable(shape):

  79. init = tf.random_normal(shape)

  80. return tf.Variable(init)

  81.  
  82. def conv2d(x, W):

  83. return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME')

  84.  
  85. def maxPool(x):

  86. return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')

  87.  
  88. def dropout(x, keep):

  89. return tf.nn.dropout(x, keep)

  90.  
  91. def cnnLayer():

  92. # 第一层

  93. W1 = weightVariable([3,3,3,32]) # 卷积核大小(3,3), 输入通道(3), 输出通道(32)

  94. b1 = biasVariable([32])

  95. # 卷积

  96. conv1 = tf.nn.relu(conv2d(x, W1) + b1)

  97. # 池化

  98. pool1 = maxPool(conv1)

  99. # 减少过拟合,随机让某些权重不更新

  100. drop1 = dropout(pool1, keep_prob_5)

  101.  
  102. # 第二层

  103. W2 = weightVariable([3,3,32,64])

  104. b2 = biasVariable([64])

  105. conv2 = tf.nn.relu(conv2d(drop1, W2) + b2)

  106. pool2 = maxPool(conv2)

  107. drop2 = dropout(pool2, keep_prob_5)

  108.  
  109. # 第三层

  110. W3 = weightVariable([3,3,64,64])

  111. b3 = biasVariable([64])

  112. conv3 = tf.nn.relu(conv2d(drop2, W3) + b3)

  113. pool3 = maxPool(conv3)

  114. drop3 = dropout(pool3, keep_prob_5)

  115.  
  116. # 全连接层

  117. Wf = weightVariable([8*16*32, 512])

  118. bf = biasVariable([512])

  119. drop3_flat = tf.reshape(drop3, [-1, 8*16*32])

  120. dense = tf.nn.relu(tf.matmul(drop3_flat, Wf) + bf)

  121. dropf = dropout(dense, keep_prob_75)

  122.  
  123. # 输出层

  124. Wout = weightVariable([512,2])

  125. bout = weightVariable([2])

  126. #out = tf.matmul(dropf, Wout) + bout

  127. out = tf.add(tf.matmul(dropf, Wout), bout)

  128. return out

  129.  
  130. def cnnTrain():

  131. out = cnnLayer()

  132.  
  133. cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=out, labels=y_))

  134.  
  135. train_step = tf.train.AdamOptimizer(0.01).minimize(cross_entropy)

  136. # 比较标签是否相等,再求的所有数的平均值,tf.cast(强制转换类型)

  137. accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(out, 1), tf.argmax(y_, 1)), tf.float32))

  138. # 将loss与accuracy保存以供tensorboard使用

  139. tf.summary.scalar('loss', cross_entropy)

  140. tf.summary.scalar('accuracy', accuracy)

  141. merged_summary_op = tf.summary.merge_all()

  142. # 数据保存器的初始化

  143. saver = tf.train.Saver()

  144.  
  145. with tf.Session() as sess:

  146.  
  147. sess.run(tf.global_variables_initializer())

  148.  
  149. summary_writer = tf.summary.FileWriter('./tmp', graph=tf.get_default_graph())

  150.  
  151. for n in range(10):

  152. # 每次取128(batch_size)张图片

  153. for i in range(num_batch):

  154. batch_x = train_x[i*batch_size : (i+1)*batch_size]

  155. batch_y = train_y[i*batch_size : (i+1)*batch_size]

  156. # 开始训练数据,同时训练三个变量,返回三个数据

  157. _,loss,summary = sess.run([train_step, cross_entropy, merged_summary_op],

  158. feed_dict={x:batch_x,y_:batch_y, keep_prob_5:0.5,keep_prob_75:0.75})

  159. summary_writer.add_summary(summary, n*num_batch+i)

  160. # 打印损失

  161. print(n*num_batch+i, loss)

  162.  
  163. if (n*num_batch+i) % 100 == 0:

  164. # 获取测试数据的准确率

  165. acc = accuracy.eval({x:test_x, y_:test_y, keep_prob_5:1.0, keep_prob_75:1.0})

  166. print(n*num_batch+i, acc)

  167. # 准确率大于0.98时保存并退出

  168. if acc > 0.98 and n > 2:

  169. saver.save(sess, './train_faces.model', global_step=n*num_batch+i)

  170. sys.exit(0)

  171. print('accuracy less 0.98, exited!')

  172.  
  173. cnnTrain()

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

使用模型进行识别

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

is_my_face.py

 
  1. output = cnnLayer()

  2. predict = tf.argmax(output, 1)

  3.  
  4. saver = tf.train.Saver()

  5. sess = tf.Session()

  6. saver.restore(sess, tf.train.latest_checkpoint('.'))

  7.  
  8. def is_my_face(image):

  9. res = sess.run(predict, feed_dict={x: [image/255.0], keep_prob_5:1.0, keep_prob_75: 1.0})

  10. if res[0] == 1:

  11. return True

  12. else:

  13. return False

  14.  
  15. #使用dlib自带的frontal_face_detector作为我们的特征提取器

  16. detector = dlib.get_frontal_face_detector()

  17.  
  18. cam = cv2.VideoCapture(0)

  19.  
  20. while True:

  21. _, img = cam.read()

  22. gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

  23. dets = detector(gray_image, 1)

  24. if not len(dets):

  25. #print('Can`t get face.')

  26. cv2.imshow('img', img)

  27. key = cv2.waitKey(30) & 0xff

  28. if key == 27:

  29. sys.exit(0)

  30.  
  31. for i, d in enumerate(dets):

  32. x1 = d.top() if d.top() > 0 else 0

  33. y1 = d.bottom() if d.bottom() > 0 else 0

  34. x2 = d.left() if d.left() > 0 else 0

  35. y2 = d.right() if d.right() > 0 else 0

  36. face = img[x1:y1,x2:y2]

  37. # 调整图片的尺寸

  38. face = cv2.resize(face, (size,size))

  39. print('Is this my face? %s' % is_my_face(face))

  40.  
  41. cv2.rectangle(img, (x2,x1),(y2,y1), (255,0,0),3)

  42. cv2.imshow('image',img)

  43. key = cv2.waitKey(30) & 0xff

  44. if key == 27:

  45. sys.exit(0)

  46.  
  47. sess.close()

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值