1. 程式人生 > >人臉識別--訓練一個認識我的神經網路

人臉識別--訓練一個認識我的神經網路

這段時間正在學習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. output_dir = './my_faces'

  7. size = 64

  8. if not os.path.exists(output_dir):

  9. os.makedirs(output_dir)

  10. # 改變圖片的亮度與對比度

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

  12. w = img.shape[1]

  13. h = img.shape[0]

  14. #image = []

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

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

  17. for c in range(3):

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

  19. if tmp > 255:

  20. tmp = 255

  21. elif tmp < 0:

  22. tmp = 0

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

  24. return img

  25. #使用dlib自帶的frontal_face_detector作為我們的特徵提取器

  26. detector = dlib.get_frontal_face_detector()

  27. # 開啟攝像頭 引數為輸入流,可以為攝像頭或視訊檔案

  28. camera = cv2.VideoCapture(0)

  29. index = 1

  30. while True:

  31. if (index <= 10000):

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

  33. # 從攝像頭讀取照片

  34. success, img = camera.read()

  35. # 轉為灰度圖片

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

  37. # 使用detector進行人臉檢測

  38. dets = detector(gray_img, 1)

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

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

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

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

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

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

  45. # 調整圖片的對比度與亮度, 對比度與亮度值都取隨機數,這樣能增加樣本的多樣性

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

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

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

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

  50. index += 1

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

  52. if key == 27:

  53. break

  54. else:

  55. print('Finished!')

  56. break

在這裡我也給出一個opencv來識別人臉的程式碼示例:

  1. import cv2

  2. import os

  3. import sys

  4. import random

  5. out_dir = './my_faces'

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

  7. os.makedirs(out_dir)

  8. # 改變亮度與對比度

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

  10. w = img.shape[1]

  11. h = img.shape[0]

  12. #image = []

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

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

  15. for c in range(3):

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

  17. if tmp > 255:

  18. tmp = 255

  19. elif tmp < 0:

  20. tmp = 0

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

  22. return img

  23. # 獲取分類器

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

  25. # 開啟攝像頭 引數為輸入流,可以為攝像頭或視訊檔案

  26. camera = cv2.VideoCapture(0)

  27. n = 1

  28. while 1:

  29. if (n <= 10000):

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

  31. # 讀幀

  32. success, img = camera.read()

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

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

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

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

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

  38. '''

  39. if n % 3 == 1:

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

  41. elif n % 3 == 2:

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

  43. '''

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

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

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

  47. n+=1

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

  49. if key == 27:

  50. break

  51. else:

  52. break

獲取其他人臉圖片集

需要收集一個其他人臉的圖片集,只要不是自己的人臉都可以,可以在網上找到,這裡我給出一個我用到的圖片集:

先將下載的圖片集,解壓到專案目錄下的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. input_dir = './input_img'

  7. output_dir = './other_faces'

  8. size = 64

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

  10. os.makedirs(output_dir)

  11. #使用dlib自帶的frontal_face_detector作為我們的特徵提取器

  12. detector = dlib.get_frontal_face_detector()

  13. index = 1

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

  15. for filename in filenames:

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

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

  18. img_path = path+'/'+filename

  19. # 從檔案讀取圖片

  20. img = cv2.imread(img_path)

  21. # 轉為灰度圖片

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

  23. # 使用detector進行人臉檢測 dets為返回的結果

  24. dets = detector(gray_img, 1)

  25. #使用enumerate 函式遍歷序列中的元素以及它們的下標

  26. #下標i即為人臉序號

  27. #left:人臉左邊距離圖片左邊界的距離 ;right:人臉右邊距離圖片左邊界的距離

  28. #top:人臉上邊距離圖片上邊界的距離 ;bottom:人臉下邊距離圖片上邊界的距離

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

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

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

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

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

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

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

  36. # 調整圖片的尺寸

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

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

  39. # 儲存圖片

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

  41. index += 1

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

  43. if key == 27:

  44. 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. my_faces_path = './my_faces'

  9. other_faces_path = './other_faces'

  10. size = 64

  11. imgs = []

  12. labs = []

  13. def getPaddingSize(img):

  14. h, w, _ = img.shape

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

  16. longest = max(h, w)

  17. if w < longest:

  18. tmp = longest - w

  19. # //表示整除符號

  20. left = tmp // 2

  21. right = tmp - left

  22. elif h < longest:

  23. tmp = longest - h

  24. top = tmp // 2

  25. bottom = tmp - top

  26. else:

  27. pass

  28. return top, bottom, left, right

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

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

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

  32. filename = path + '/' + filename

  33. img = cv2.imread(filename)

  34. top,bottom,left,right = getPaddingSize(img)

  35. # 將圖片放大, 擴充圖片邊緣部分

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

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

  38. imgs.append(img)

  39. labs.append(path)

  40. readData(my_faces_path)

  41. readData(other_faces_path)

  42. # 將圖片資料與標籤轉換成陣列

  43. imgs = np.array(imgs)

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

  45. # 隨機劃分測試集與訓練集

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

  47. # 引數:圖片資料的總數,圖片的高、寬、通道

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

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

  50. # 將資料轉換成小於1的數

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

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

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

  54. # 圖片塊,每次取100張圖片

  55. batch_size = 100

  56. num_batch = len(train_x) // batch_size

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

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

  59. keep_prob_5 = tf.placeholder(tf.float32)

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

  61. def weightVariable(shape):

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

  63. return tf.Variable(init)

  64. def biasVariable(shape):

  65. init = tf.random_normal(shape)

  66. return tf.Variable(init)

  67. def conv2d(x, W):

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

  69. def maxPool(x):

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

  71. def dropout(x, keep):

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

  73. def cnnLayer():

  74. # 第一層

  75. W1 = weightVariable([3,3,3,32]) # 卷積核大小(3,3), 輸入通道(3), 輸出通道(32)

  76. b1 = biasVariable([32])

  77. # 卷積

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

  79. # 池化

  80. pool1 = maxPool(conv1)

  81. # 減少過擬合,隨機讓某些權重不更新

  82. drop1 = dropout(pool1, keep_prob_5)

  83. # 第二層

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

  85. b2 = biasVariable([64])

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

  87. pool2 = maxPool(conv2)

  88. drop2 = dropout(pool2, keep_prob_5)

  89. # 第三層

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

  91. b3 = biasVariable([64])

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

  93. pool3 = maxPool(conv3)

  94. drop3 = dropout(pool3, keep_prob_5)

  95. # 全連線層

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

  97. bf = biasVariable([512])

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

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

  100. dropf = dropout(dense, keep_prob_75)

  101. # 輸出層

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

  103. bout = weightVariable([2])

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

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

  106. return out

  107. def cnnTrain():

  108. out = cnnLayer()

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

  110. train_step = tf.train.AdamOptimizer(0.01).minimize(cross_entropy)

  111. # 比較標籤是否相等,再求的所有數的平均值,tf.cast(強制轉換型別)

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

  113. # 將loss與accuracy儲存以供tensorboard使用

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

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

  116. merged_summary_op = tf.summary.merge_all()

  117. # 資料儲存器的初始化

  118. saver = tf.train.Saver()

  119. with tf.Session() as sess:

  120. sess.run(tf.global_variables_initializer())

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

  122. for n in range(10):

  123. # 每次取128(batch_size)張圖片

  124. for i in range(num_batch):

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

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

  127. # 開始訓練資料,同時訓練三個變數,返回三個資料

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

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

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

  131. # 列印損失

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

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

  134. # 獲取測試資料的準確率

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

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

  137. # 準確率大於0.98時儲存並退出

  138. if acc > 0.98 and n > 2:

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

  140. sys.exit(0)

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

  142. cnnTrain()

訓練之後的資料會儲存在當前目錄下。

使用模型進行識別

最後就是讓她認識我了,很簡單,只要執行程式,讓攝像頭拍到我的臉,她就可以輕鬆地識別出是不是我了。

is_my_face.py

  1. output = cnnLayer()

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

  3. saver = tf.train.Saver()

  4. sess = tf.Session()

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

  6. def is_my_face(image):

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

  8. if res[0] == 1:

  9. return True

  10. else:

  11. return False

  12. #使用dlib自帶的frontal_face_detector作為我們的特徵提取器

  13. detector = dlib.get_frontal_face_detector()

  14. cam = cv2.VideoCapture(0)

  15. while True:

  16. _, img = cam.read()

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

  18. dets = detector(gray_image, 1)

  19. if not len(dets):

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

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

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

  23. if key == 27:

  24. sys.exit(0)

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

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

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

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

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

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

  31. # 調整圖片的尺寸

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

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

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

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

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

  37. if key == 27:

  38. sys.exit(0)

  39. sess.close()