版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cicilover/article/details/77865336
特征脸技术是近期发展起来的用于人脸或者一般性刚体识别以及其它涉及到人脸处理的一种方法。首先把一批人脸图像转换成一个特征向量集,称为
“Eigenfaces”
,即
“
特征脸
”
,它们是最初训练图像集的基本组件。识别的过程是把一副新的图像投影到特征脸子空间,并通过它的投影点在子空间的位置以及投影线的长度来进行判定和识别。
将图像变换到另一个空间后,同一个类别的图像会聚到一起,不同类别的图像会聚力比较远,在原像素空间中不同类别的图像在分布上很难用简单的线或者面切分,变换到另一个空间,就可以很好的把他们分开了。
Eigenfaces
选择的空间变换方法是
PCA
(主成分分析),利用
PCA
得到人脸分布的主要成分,具体实现是对训练集中所有人脸图像的协方差矩阵进行本征值分解,得到对应的本征向量,这些本征向量就是
“
特征脸
”
。
每个特征向量或者特征脸相当于捕捉或者描述人脸之间的一种变化或者特性。这就意味着每个人脸都可以表示为这些特征脸的线性组合。
下面就直接给出基于特征脸的人脸识别实现过程:
原始图像投影到该特征空间中。特别说明,此时的原始图像
x
存成大小是
n
维的向量,即:
训练集为(这里
p
为样本图像数量),形成矩阵
X[n][p]
,其中行代表像元,列代表每幅人脸图像。
将训练样本集中的人脸图像减去平均人脸图像,计算离散差值,将训练图像中心化。
将中心化之后图像组成一个大小为
n
×
p
的矩阵
X
:
将中心化后的图像组成的矩阵
X
乘以它的转置矩阵得到协方差矩阵Ω:
求解协方差矩阵Ω的
k
个非零特征值,以及所对应的特征向量
,
一般来说,训练图像数量
p
远远小于一幅图像的像素值
n
,所以协方差矩阵
Ω
最多有对应于非零特征值的
p
个特征向量,所以
k≤p.
按照特征值的从大到小的顺序排列特征向量,对应于最大特征值的特征向量反应了训练图像间的最大差异,而对应的特征值越小的特征向量,反应的图像间的差异越小。所有的非零特征值对应的特征向量
,
组成特征空间,也就是所谓的
“
特征脸
”
空间。
计算特征值和特征向量,其中
U
为对应于特征值
的特征向集。排列特征向量:按照非零特征值,从大到小的顺序,将对应的特征向量排列。所组成的特征向量矩阵即为特征空间
U
,
U
的每一列为一个特征向量:
这样每一幅人脸图像都可以投影到由张成的子空间中。因此每一幅人脸图像对应于子空间中的一个点,同样,子空间中的每个点对应于一幅图像,下图
显示的是
所对应的图像,由于这些图像很像人脸,所以它们被称为
“
特征脸
”
。
特征脸
训练图像投影得到特征脸子空间
有了这样一个由
“
特征脸
”
组成的降维特征子空间,任何一幅中心化后的人脸图像都可以通过下面的式子投影到特征脸子空间并获得一组坐标系数:
本文采用的数据集为“Labeled Faces in the Wild”, aka LFW: http://vis-www.cs.umass.edu/lfw/lfw-funneled.tgz (233MB)
下面结合Eigenfaces和SVM进行人脸识别:
Python源码:
from __future__ import print_function
from time import time
import logging
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import fetch_lfw_people
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.decomposition import PCA
from sklearn.svm import SVC
print(__doc__)
# Display progress logs on stdout
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
# #############################################################################
# Download the data, if not already on disk and load it as numpy arrays
lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)
# introspect the images arrays to find the shapes (for plotting)
n_samples, h, w = lfw_people.images.shape
# for machine learning we use the 2 data directly (as relative pixel
# positions info is ignored by this model)
X = lfw_people.data
n_features = X.shape[1]
# the label to predict is the id of the person
y = lfw_people.target
target_names = lfw_people.target_names
n_classes = target_names.shape[0]
print("Total dataset size:")
print("n_samples: %d" % n_samples)
print("n_features: %d" % n_features)
print("n_classes: %d" % n_classes)
# #############################################################################
# Split into a training set and a test set using a stratified k fold
# split into a training and testing set
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42)
# #############################################################################
# Compute a PCA (eigenfaces) on the face dataset (treated as unlabeled
# dataset): unsupervised feature extraction / dimensionality reduction
n_components = 150
print("Extracting the top %d eigenfaces from %d faces"
% (n_components, X_train.shape[0]))
t0 = time()
pca = PCA(n_components=n_components, svd_solver='randomized',
whiten=True).fit(X_train)
print("done in %0.3fs" % (time() - t0))
eigenfaces = pca.components_.reshape((n_components, h, w))
print("Projecting the input data on the eigenfaces orthonormal basis")
t0 = time()
X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)
print("done in %0.3fs" % (time() - t0))
# #############################################################################
# Train a SVM classification model
print("Fitting the classifier to the training set")
t0 = time()
param_grid = {'C': [1e3, 5e3, 1e4, 5e4, 1e5],
'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], }
clf = GridSearchCV(SVC(kernel='rbf', class_weight='balanced'), param_grid)
clf = clf.fit(X_train_pca, y_train)
print("done in %0.3fs" % (time() - t0))
print("Best estimator found by grid search:")
print(clf.best_estimator_)
# #############################################################################
# Quantitative evaluation of the model quality on the test set
print("Predicting people's names on the test set")
t0 = time()
y_pred = clf.predict(X_test_pca)
print("done in %0.3fs" % (time() - t0))
print(classification_report(y_test, y_pred, target_names=target_names))
print(confusion_matrix(y_test, y_pred, labels=range(n_classes)))
# #############################################################################
# Qualitative evaluation of the predictions using matplotlib
def plot_gallery(images, titles, h, w, n_row=3, n_col=4):
"""Helper function to plot a gallery of portraits"""
plt.figure(figsize=(1.8 * n_col, 2.4 * n_row))
plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)
for i in range(n_row * n_col):
plt.subplot(n_row, n_col, i + 1)
plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray)
plt.title(titles[i], size=12)
plt.xticks(())
plt.yticks(())
# plot the result of the prediction on a portion of the test set
def title(y_pred, y_test, target_names, i):
pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1]
true_name = target_names[y_test[i]].rsplit(' ', 1)[-1]
return 'predicted: %s\ntrue: %s' % (pred_name, true_name)
prediction_titles = [title(y_pred, y_test, target_names, i)
for i in range(y_pred.shape[0])]
plot_gallery(X_test, prediction_titles, h, w)
# plot the gallery of the most significative eigenfaces
eigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])]
plot_gallery(eigenfaces, eigenface_titles, h, w)
plt.show()
Result: