实验 2:基于 ORL 人脸库,实验样本主要来自于两个人,每人 45 张图片,共有 90 个样本,其中的 80 个样本作为训练样本,10 个作为测试样本。通过 LDA 实现两类问题的线性判别。 一个Fisher线性分类器讲解的不错的博客:参考博客 与上篇博客的基本内容相差不多,但是相比起上篇中的数据,本次实验多了对人脸数据的处理。
def Get_img(file_path):
train_set = np.zeros(shape=[1,32*32])
for filename in os.listdir(file_path):
img = cv2.imread(file_path+'/'+filename,cv2.IMREAD_GRAYSCALE)
n,m = img.shape
res = img.reshape(1,n*m).tolist()
train_set = np.row_stack((train_set,res))
return train_set
Fisher函数
def Fisher(w1,w2):
w1 = w1.T
w2 = w2.T
sz1 = np.size(w1,1)
sz2 = np.size(w2,1)
avg1 = np.mean(w1,axis=1)
avg2 = np.mean(w2,axis=1)
s1 = np.zeros((w1.shape[0],w1.shape[0]))
n,m = w1.shape
for i in range(m):
tmp = w1[:,i] - avg1
s1 = s1 + tmp*tmp.T
s2 = np.zeros((w2.shape[0], w2.shape[0]))
n, m = w2.shape
for i in range(m):
tmp = w2[:,i] - avg2
s2 = s2 + tmp*tmp.T
Sw = s1+s2
w_x = np.linalg.inv(Sw)*(avg1-avg2)
res1 = 0
for i in range(sz1):
res1 = res1 + w_x.T * w1[:, i]
res2 = 0
for i in range(sz2):
res2 = res2 + w_x.T * w2[:, i]
return -(res1 + res2) / (sz1 + sz2), w_x
测试数据如下所示:其中前5个属于第一类,后5个属于第二类。 测试结果如下:第六个人貌似判断出错了-_-
D:\ProgramData\Anaconda3\python.exe E:/Users/yqx/PycharmProjects/Fisher_Face_Rec/main.py
The First Man
The First Man
The First Man
The First Man
The First Man
The First Man
The Second Man
The Second Man
The Second Man
The Second Man
Process finished with exit code 0
努力加油a啊
|