[关闭]
@Metralix 2019-08-22T15:06:59.000000Z 字数 10542 阅读 634

实验代码-李昊洋

人脸识别


  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Aug 13 21:08:18 2019
  4. @author: 54164
  5. """
  6. import numpy as np
  7. import matplotlib.pyplot as plt
  8. import time
  9. import LRA_GL_utils as utils
  10. import data_pre_process as dprocess
  11. time_start=time.time()
  12. #train_vis,train_nir,test_vis,test_nir =utils.readPicture(folder_path="./dataset_CASIA")
  13. #train_vis = np.load('train_vis.npy')
  14. #train_nir = np.load('train_nir.npy')
  15. #test_vis = np.load('test_vis.npy')
  16. #test_nir = np.load('test_nir.npy')
  17. #pre process the pictures
  18. #dprocess.cut_face_into_folder(train_vis,"train_vis_face")
  19. #dprocess.cut_face_into_folder(train_nir,"train_nir_face")
  20. #dprocess.cut_face_into_folder(test_vis,"test_vis_face")
  21. #dprocess.cut_face_into_folder(test_nir,"test_nir_face")
  22. train_vis_face,train_nir_face,test_vis_face,test_nir_face = dprocess.reload_new_faces()
  23. dprocess.rename_pictures()
  24. k = test_nir_face.shape[0]
  25. m = train_nir_face.shape[0]
  26. Y_gl = np.hstack((np.eye(k),np.zeros([k,m])))
  27. #Y_gl = np.hstack((np.eye(k),np.zeros([k,1000])))
  28. probe = utils.lbp_encode(test_nir_face)
  29. print("encoded test_nir !!!")
  30. X = utils.lbp_encode(test_vis_face)
  31. print("encoded test_vis !!!")
  32. variants = utils.intro_class_variant(train_vis_face,train_nir_face)
  33. print("extracted the varients !!!")
  34. variants_lbp = utils.lbp_encode(variants)
  35. print("encoded varients !!!")
  36. X_gl = np.hstack((X,variants_lbp))
  37. #X_gl = np.hstack((X,variants_lbp[:,0:1000]))
  38. X_gl_mat = np.mat(X_gl)
  39. X_gl_inv = X_gl_mat.I
  40. X_gl_inv = np.array(X_gl_inv)
  41. W_gl = np.dot(Y_gl,X_gl_inv)
  42. Y_gl_hat = np.dot(W_gl,probe)
  43. accuracy = utils.calculate_accuracy(Y_gl_hat)
  44. accuracy_top5 = utils.calculate_accuracy_top5(Y_gl_hat)
  45. time_end=time.time()
  46. print('totally cost : ',time_end-time_start)

功能:
读入数据集,lbp编码,计算类内变化基,计算基准度

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Fri Aug 9 21:00:10 2019
  4. @author: haoyang li
  5. """
  6. import numpy as np
  7. import math
  8. import matplotlib.pyplot as plt
  9. import matplotlib.image as mpimg
  10. import os
  11. import cv2
  12. """
  13. function:read the picture from the os folder
  14. input:folder path
  15. output:(train_vis,train_nir,gallary,probe) in the format of matrix
  16. """
  17. def readPicture(folder_path=r"C:\Users\54164\Desktop\LRA_GL\dataset_CASIA"):
  18. #读取 train_vis 训练的彩色照片,并转化为灰度图
  19. train_vis = []
  20. for i in range(30840):
  21. train_vis_path = os.path.join(folder_path,'train_vis','{0:05d}.jpg'.format(i+1))
  22. if os.path.exists(train_vis_path):
  23. #I = mpimg.imread(train_vis_path)
  24. I = cv2.imread(train_vis_path,cv2.IMREAD_GRAYSCALE)
  25. train_vis.append(I)
  26. print("readed train_vis")
  27. #读取 train_nir 训练的黑白照片
  28. train_nir = []
  29. for i in range(30840):
  30. suffix = ['a','b','c','d','e']
  31. path_a = os.path.join(folder_path,'train_nir','{0:05d}_a.jpg'.format(i+1))
  32. if os.path.exists(path_a):
  33. for c in suffix:
  34. path_all = os.path.join(folder_path,'train_nir','{0:05d}_{1}.jpg'.format(i+1,c))
  35. #I = mpimg.imread(path_all)
  36. I = cv2.imread(path_all,cv2.IMREAD_GRAYSCALE)
  37. train_nir.append(I)
  38. print("readed train_nir")
  39. #读取 test_vis gallary 测试的彩照
  40. test_vis = []
  41. for i in range(30840):
  42. test_vis_path = os.path.join(folder_path,'test_vis','{0:05d}.jpg'.format(i+1))
  43. if os.path.exists(test_vis_path):
  44. #I = mpimg.imread(test_vis_path)
  45. I = cv2.imread(test_vis_path,cv2.IMREAD_GRAYSCALE)
  46. test_vis.append(I)
  47. print("readed test_vis")
  48. #读取 test_nir probe 测试的黑白照
  49. test_nir = []
  50. for i in range(30840):
  51. test_nir_path = os.path.join(folder_path,'test_nir','{0:05d}.jpg'.format(i+1))
  52. if os.path.exists(test_nir_path):
  53. #I = mpimg.imread(test_nir_path)
  54. I = cv2.imread(test_nir_path,cv2.IMREAD_GRAYSCALE)
  55. test_nir.append(I)
  56. print("readed test_nir")
  57. return np.array(train_vis),np.array(train_nir),np.array(test_vis),np.array(test_nir)
  58. """
  59. lbp encode the picture set
  60. input:picture sets of 2d or 3d reality photos
  61. output:lbp code set of these pictures
  62. """
  63. def lbp_encode(picture_set,cell_size=20):
  64. for i in range(picture_set.shape[0]):
  65. if i % 50 == 0:
  66. print("read set's no. {0} pictures".format(i))
  67. hist = np.zeros(256*cell_size*cell_size)
  68. hist_idx = 0
  69. pic = picture_set[i,:,:].copy()
  70. height = math.floor(pic.shape[0]/cell_size) #20
  71. width = math.floor(pic.shape[1]/cell_size) #20
  72. for cell_x in range(cell_size): #0-10
  73. for cell_y in range(cell_size):
  74. for x in range(width):
  75. x = x + cell_x * width
  76. for y in range(height):
  77. y = y + cell_y * height
  78. if x-2>=0 and y-2>=0 and x+2<pic.shape[1] and y+2<pic.shape[0]: #边界值忽略
  79. code = []
  80. code.append(pic[y-1,x-1]>pic[y,x])
  81. code.append(pic[y,x-1]>pic[y,x])
  82. code.append(pic[y+1,x-1]>pic[y,x])
  83. code.append(pic[y+1,x]>pic[y,x])
  84. code.append(pic[y+1,x+1]>pic[y,x])
  85. code.append(pic[y,x+1]>pic[y,x])
  86. code.append(pic[y-1,x+1]>pic[y,x])
  87. code.append(pic[y-1,x]>pic[y,x])
  88. code = np.array(code)
  89. code = code + 0
  90. code = bin2oct(code)
  91. hist[code + hist_idx*256] += 1
  92. hist_idx += 1
  93. hist = hist/(height*width)
  94. hist = hist.reshape([256*cell_size*cell_size,1])
  95. # normalized to zeros mean and unit length.
  96. hist = hist - np.mean(hist)
  97. sum_square = math.sqrt(np.sum(hist**2))
  98. hist = hist/sum_square
  99. if i == 0:
  100. coverted_matrix = hist.copy()
  101. else:
  102. coverted_matrix = np.hstack((coverted_matrix,hist.copy()))
  103. return coverted_matrix
  104. """
  105. calculate the intro_class variants
  106. input:the train_vis and trian_nir datasets
  107. output:get the intro_class variant of the trian datasets
  108. the out size is the same as a 840*480 gary picture
  109. """
  110. def intro_class_variant(vis_pics,nir_pics):
  111. variant_set = []
  112. for i in range(nir_pics.shape[0]):
  113. pic = nir_pics[i,:,:]-vis_pics[i//5,:,:]
  114. #pic = vis_pics[i//5,:,:] - nir_pics[i,:,:]
  115. variant_set.append(pic.copy())
  116. return np.array(variant_set)
  117. """
  118. input:result matrix of the algorithm
  119. output:calculate the accuracy of the model
  120. """
  121. def calculate_accuracy(res_matrix):
  122. res_matrix = res_matrix + 10
  123. max_list = np.max(res_matrix,axis=0)
  124. for i in range(res_matrix.shape[1]):
  125. res_matrix[:,i] = res_matrix[:,i]-max_list[i]+1e-5
  126. res_matrix = res_matrix >= 0
  127. correct_cnt = 0
  128. for i in range(res_matrix.shape[1]):
  129. if res_matrix[i,i] == 1:
  130. correct_cnt += 1
  131. return correct_cnt / res_matrix.shape[1]
  132. """
  133. input:result matrix of the algorithm
  134. output:calculate the accuracy_top5 of the model
  135. """
  136. def calculate_accuracy_top5(res_matrix):
  137. res_matrix = res_matrix + 10
  138. #max_list = np.max(res_matrix,axis=0)
  139. max5_list = []
  140. for i in range(res_matrix.shape[1]):
  141. cow_list = res_matrix[:,i].copy()
  142. cow_list.sort()
  143. max5_list.append(cow_list[res_matrix.shape[0]-5])
  144. for i in range(res_matrix.shape[1]):
  145. res_matrix[:,i] = res_matrix[:,i]-max5_list[i]+1e-5
  146. res_matrix = res_matrix >= 0
  147. correct_cnt = 0
  148. for i in range(res_matrix.shape[1]):
  149. if res_matrix[i,i] == 1:
  150. correct_cnt += 1
  151. else:
  152. print("no.{}th pic is wrong!!!".format(i))
  153. return correct_cnt / res_matrix.shape[1]
  154. def calculate_accuracy_top10(res_matrix):
  155. res_matrix = res_matrix + 10
  156. #max_list = np.max(res_matrix,axis=0)
  157. max5_list = []
  158. for i in range(res_matrix.shape[1]):
  159. cow_list = res_matrix[:,i].copy()
  160. cow_list.sort()
  161. max5_list.append(cow_list[res_matrix.shape[0]-10])
  162. for i in range(res_matrix.shape[1]):
  163. res_matrix[:,i] = res_matrix[:,i]-max5_list[i]+1e-5
  164. res_matrix = res_matrix >= 0
  165. correct_cnt = 0
  166. for i in range(res_matrix.shape[1]):
  167. if res_matrix[i,i] == 1:
  168. correct_cnt += 1
  169. return correct_cnt / res_matrix.shape[1]
  170. """
  171. transform the RGB pattern into gray
  172. """
  173. def rgb2gray(rgb):
  174. return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])
  175. """
  176. transform the bin array into an oct number
  177. """
  178. def bin2oct(bin_list):
  179. summ = 0
  180. for i in range(len(bin_list)):
  181. summ += int(bin_list[len(bin_list)-1-i])*pow(2,i)
  182. return summ

功能
从数据集中提取人脸写入另一个文件夹,从新读取人脸数据

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Aug 13 20:56:28 2019
  4. @author: 54164
  5. """
  6. import cv2
  7. import os
  8. import numpy as np
  9. import matplotlib.pyplot as plt
  10. from shutil import copyfile
  11. def cut_face_into_folder(data_set,folder_name):
  12. face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
  13. face_set = []
  14. for i in range(data_set.shape[0]):
  15. img = np.array(data_set[i,:,:],dtype='uint8')
  16. face = face_cascade.detectMultiScale(img, scaleFactor=1.1, minNeighbors=15, minSize=(150, 150), flags=cv2.CASCADE_SCALE_IMAGE)
  17. if face != ():
  18. print("readed {0} faces".format(i))
  19. x = face[0,0]
  20. y = face[0,1]
  21. w = face[0,2]
  22. h = face[0,3]
  23. #face_set.append(img[y:y+h,x:x+w].copy())
  24. img_new = cv2.resize(img[y:y+h,x:x+w].copy(), (200,200), interpolation = cv2.INTER_AREA )
  25. img_new = cv2.resize(img_new[10:190,25:175], (150,150), interpolation = cv2.INTER_AREA )
  26. cv2.imwrite("./{0}/{1}.jpg".format(folder_name,i),img_new)
  27. print("saved {0} faces in {1}".format(i,folder_name))
  28. else:
  29. print("Ooops!!!!!!!!!")
  30. def reload_new_faces(train_vis_path="./face\train_vis_face",
  31. train_nir_path="./face\train_nir_face",
  32. test_vis_path="./face\test_vis_face",
  33. test_nir_path="./face\test_nir_face",):
  34. # test_nir and test_vis
  35. test_nir = []
  36. test_vis = []
  37. for i in range(360):
  38. test_nir_path_all = os.path.join(test_nir_path,"{0}.jpg".format(i))
  39. test_vis_path_all = os.path.join(test_vis_path,"{0}.jpg".format(i))
  40. if os.path.exists(test_nir_path_all) and os.path.exists(test_vis_path_all):
  41. test_nir.append(cv2.imread(test_nir_path_all,cv2.IMREAD_GRAYSCALE))
  42. test_vis.append(cv2.imread(test_vis_path_all,cv2.IMREAD_GRAYSCALE))
  43. elif os.path.exists(test_nir_path_all):
  44. os.remove(test_nir_path_all)
  45. elif os.path.exists(test_vis_path_all):
  46. os.remove(test_vis_path_all)
  47. # train_vis and train_nir
  48. train_vis = []
  49. train_nir = []
  50. for i in range(360):
  51. train_vis_path_all = os.path.join(train_vis_path,"{0}.jpg".format(i))
  52. if os.path.exists(train_vis_path_all):
  53. nir_all_exist = True
  54. for j in range(5):
  55. if os.path.exists(os.path.join(train_nir_path,"{0}.jpg".format(i*5+j))) == False:
  56. nir_all_exist = False
  57. if nir_all_exist:
  58. for j in range(5):
  59. train_nir_path_all = os.path.join(train_nir_path,"{0}.jpg".format(i*5+j))
  60. train_nir.append(cv2.imread(train_nir_path_all,cv2.IMREAD_GRAYSCALE))
  61. train_vis.append(cv2.imread(train_vis_path_all,cv2.IMREAD_GRAYSCALE))
  62. else:
  63. for j in range(5):
  64. train_nir_path_all = os.path.join(train_nir_path,"{0}.jpg".format(i*5+j))
  65. if os.path.exists(train_nir_path_all):
  66. os.remove(train_nir_path_all)
  67. os.remove(train_vis_path_all)
  68. return np.array(train_vis),np.array(train_nir),np.array(test_vis),np.array(test_nir)
  69. def rename_pictures(train_vis_path="./train_vis_face",
  70. train_nir_path="./train_nir_face",
  71. test_vis_path="./test_vis_face",
  72. test_nir_path="./test_nir_face",):
  73. # rename
  74. if os.path.exists(os.path.join(train_vis_path,"new")) == False:
  75. os.mkdir(os.path.join(train_vis_path,"new"))
  76. idx = 0
  77. for i in range(360):
  78. train_vis_path_all = os.path.join(train_vis_path,"{0}.jpg".format(i))
  79. if os.path.exists(train_vis_path_all):
  80. copyfile(train_vis_path_all,os.path.join(train_vis_path,"new","{0}.jpg".format(idx)))
  81. idx += 1
  82. if os.path.exists(os.path.join(train_nir_path,"new")) == False:
  83. os.mkdir(os.path.join(train_nir_path,"new"))
  84. idx = 0
  85. for i in range(360):
  86. train_nir_path_all = os.path.join(train_nir_path,"{0}.jpg".format(i))
  87. if os.path.exists(train_nir_path_all):
  88. copyfile(train_nir_path_all,os.path.join(train_nir_path,"new","{0}.jpg".format(idx)))
  89. idx += 1
  90. if os.path.exists(os.path.join(test_vis_path,"new")) == False:
  91. os.mkdir(os.path.join(test_vis_path,"new"))
  92. idx = 0
  93. for i in range(360):
  94. test_vis_path_all = os.path.join(test_vis_path,"{0}.jpg".format(i))
  95. if os.path.exists(test_vis_path_all):
  96. copyfile(test_vis_path_all,os.path.join(test_vis_path,"new","{0}.jpg".format(idx)))
  97. idx += 1
  98. if os.path.exists(os.path.join(test_nir_path,"new")) == False:
  99. os.mkdir(os.path.join(test_nir_path,"new"))
  100. idx = 0
  101. for i in range(360):
  102. test_nir_path_all = os.path.join(test_nir_path,"{0}.jpg".format(i))
  103. if os.path.exists(test_nir_path_all):
  104. copyfile(test_nir_path_all,os.path.join(test_nir_path,"new","{0}.jpg".format(idx)))
  105. idx += 1
  106. print("rename finished!!")
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注