Eigenface与PCA人脸识别算法实验

简单的特征脸识别实验


实现特征脸的过程其实就是主成分分析(Principal Component Analysis,PCA)的一个过程。关于PCA的原理问题,它是一种数学降维的方法。是为了简化问题。在二维的坐标空间内,找到一个单位向量U,使得全部数据在U上的投影之和最大。这样就能把数据分的尽量的开。而后把训练样本投影到这个向量U上,把测试图片也投影上去,计算这个投影与各个样本人脸投影的欧式距离,得出最小的欧式距离的的那个样本编号,就是最大几率的人脸。算法

Eigenface算法


特征脸方法(Eigenface)是一个经典算法的人脸识别算法。特征脸方法是从PCA导出的一种人脸识别和描述技术。就是将包含人脸的图像区域看做是一种随机向量,所以能够采用K-L变换得到其正交K-L基底。对应其中较大特征值的基底具备与人脸类似的形状,所以又称为特征脸。利用这些基底的线性组合能够描述、表达和逼近人脸图像,所以能够进行人脸识别与合成。识别过程就是将人脸图像映射到由特征脸构成的子空间上,比较其与己知人脸在特征空间中的位置,具体步骤以下:数据库

(1) 初始化,得到人脸图像的训练集并计算特征脸,定义为人脸空间,存储在模板库中,以便系统进行识别;这里使用Yalefaces数据库。这里面有15我的,每一个人的文件夹中取一张正常状态的图像,size为(98,116),并用flatten()把该图像转换成一维向量。15张这样的图组成一个(8100,15)的矩阵;app

(2) 对每一行求均值,获得一个(11368,1)的向量avgImg,这个图像就是平均脸;测试

(3) 将图像矩阵与平均脸相减,获得误差值diffTrain,用误差值计算协方差,协方差矩阵C= XXTspa

(4) 这里须要作一个变换,由于C算出来为都会很是大,能够改成计算C’,设C’ = XTX,设这里算出的特征向量为E’,XE’= E,这里E就是本来该C获得的特征向量。而后把E归一化。code

人脸识别


这里获得了15个特征脸以后,考虑选择出主成分。这里取特征向量超过特征向量均值的80%的几个特征向量,假设是K个,这K个特征向量组成的矩阵设为w。将误差矩阵转置乘以w,获得协方差矩阵的特征向量。orm

(1) 输入新的人脸图像,转换成一维向量,将其映射到特征脸空间,获得一组关于该人脸的特征数据;blog

(2) 经过检查图像与人脸空间的距离判断它是不是人脸;图片

(3) 若为人脸,根据权值模式判断它是否为数据库中的某我的,并作出具体的操做。ip

代码以下:

  1 import numpy as np
  2 
  3 from numpy import *
  4 
  5 from numpy import linalg as la
  6 
  7 from PIL import Image
  8 
  9 import glob
 10 
 11 from matplotlib import pyplot as plt
 12 
 13 def loadImageSet(add):
 14 
 15  filenames = glob.glob('face/pgm/*.pgm')
 16 
 17  filenames.sort()
 18 
 19  img = [Image.open(fn).convert('L').resize((98, 116)) for fn in filenames]
 20 
 21  FaceMat = np.asarray([np.array(im).flatten() for im in img])
 22 
 23  return FaceMat
 24 
 25 def ReconginitionVector(selecthr = 0.8):
 26 
 27  # step1: load the face image data ,get the matrix consists of all image
 28 
 29  FaceMat = loadImageSet('face/yalefaces/')
 30 
 31  print('-----------FaceMat.shape--------')
 32 
 33  print(FaceMat.shape)
 34 
 35  # step2: average the FaceMat
 36 
 37  avgImg = mean(FaceMat,0)
 38 
 39  # step3: calculate the difference of avgimg and all image data(FaceMat)
 40 
 41  diffTrain = FaceMat-avgImg
 42 
 43  covMat =np.asmatrix(diffTrain) * np.asmatrix(diffTrain.T)
 44 
 45  eigvals,eigVects = linalg.eig(covMat) #la.linalg.eig(np.mat(covMat))
 46 
 47  #step4: calculate eigenvector of covariance matrix (because covariance matrix will cause memory error)
 48 
 49  eigSortIndex = argsort(-eigvals)
 50 
 51  for i in range(shape(FaceMat)[1]):
 52 
 53  if (eigvals[eigSortIndex[:i]]/eigvals.sum()).sum() >= selecthr:
 54 
 55  eigSortIndex = eigSortIndex[:i]
 56 
 57  break
 58 
 59  covVects = diffTrain.T * eigVects[:,eigSortIndex] # covVects is the eigenvector of covariance matrix
 60 
 61  # avgImg 是均值图像,covVects是协方差矩阵的特征向量,diffTrain是误差矩阵
 62 
 63  return avgImg,covVects,diffTrain
 64 
 65 def judgeFace(judgeImg,FaceVector,avgImg,diffTrain):
 66 
 67  diff = judgeImg - avgImg
 68 
 69  weiVec = FaceVector.T* diff.T
 70 
 71  res = 0
 72 
 73  resVal = inf
 74 
 75 #==============================================================================
 76 
 77 # plt.imshow(avgImg.reshape(98,116))
 78 
 79 # plt.show()
 80 
 81 #==============================================================================
 82 
 83  for i in range(15):
 84 
 85  TrainVec = (diffTrain[i]*FaceVector).T
 86 
 87  if (array(weiVec-TrainVec)**2).sum() < resVal:
 88 
 89  res = i
 90 
 91  resVal = (array(weiVec-TrainVec)**2).sum()
 92 
 93  return res+1
 94 
 95 if __name__ == '__main__':
 96 
 97  avgImg,FaceVector,diffTrain = ReconginitionVector(selecthr = 0.8)
 98 
 99  nameList = ['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15']
100 
101  characteristic = ['centerlight','glasses','happy','leftlight','noglasses','rightlight','sad','sleepy','surprised','wink']
102 
103  for c in characteristic:
104 
105  count = 0
106 
107  for i in range(len(nameList)):
108 
109  # 这里的loadname就是咱们要识别的未知人脸图,咱们经过15张未知人脸找出的对应训练人脸进行对比来求出正确率
110 
111  loadname = 'face/yalefaces/subject'+nameList[i]+'.'+c+'.pgm'
112 
113  judgeImg = Image.open(loadname).convert('L').resize((98, 116))
114 
115  #print(loadname)
116 
117  if judgeFace(mat(judgeImg).flatten(),FaceVector,avgImg,diffTrain) == int(nameList[i]):
118 
119  count += 1
120 
121 print('accuracy of %s is %f'%(c, float(count)/len(nameList))) # 求出正确率

运行结果:

 1 accuracy of centerlight is 0.400000
 2 
 3 accuracy of glasses is 0.533333
 4 
 5 accuracy of happy is 0.866667
 6 
 7 accuracy of leftlight is 0.133333
 8 
 9 accuracy of noglasses is 0.800000
10 
11 accuracy of rightlight is 0.133333
12 
13 accuracy of sad is 0.800000
14 
15 accuracy of sleepy is 0.800000
16 
17 accuracy of surprised is 0.666667
18 
19 accuracy of wink is 0.600000
相关文章
相关标签/搜索