一、代码实现
1. 数据预处理
function processedImg = preprocess(img)% 灰度化grayImg = rgb2gray(img);% 直方图均衡化equalizedImg = histeq(grayImg);% 归一化尺寸processedImg = imresize(equalizedImg, [100, 100]);
end
2. 特征提取(PCA降维)
function features = extractFeatures(images)% 将图像矩阵转换为特征向量[numSamples, height, width] = size(images);imgVectors = double(reshape(images, numSamples, height*width));% 计算均值脸meanFace = mean(imgVectors, 1);centered = imgVectors - meanFace;% 使用SVD计算特征向量[U, ~, ~] = svd(centered' * centered);eigFaces = U(:, 1:50); % 取前50个主成分% 投影到特征空间features = centered * eigFaces;
end
3. KNN分类器训练
% 加载ORL数据集(示例)
load('orl_faces.mat'); % 包含trainData/trainLabels和testData/testLabels% 预处理数据
trainDataProc = arrayfun(@(i) preprocess(trainData(:,:,i)), 1:size(trainData,3), 'UniformOutput', false);
testDataProc = arrayfun(@(i) preprocess(testData(:,:,i)), 1:size(testData,3), 'UniformOutput', false);% 提取特征
trainFeatures = extractFeatures(trainDataProc);
testFeatures = extractFeatures(testDataProc);% 构建KNN模型
k = 5; % 近邻数
mdl = fitcknn(trainFeatures, trainLabels, 'NumNeighbors', k, 'Distance', 'euclidean');
4. 人脸识别测试
% 预测测试集
predictedLabels = predict(mdl, testFeatures);% 计算识别率
accuracy = sum(predictedLabels == testLabels) / numel(testLabels);
disp(['识别准确率: ', num2str(accuracy*100), '%']);
二、优化
1. 多尺度特征提取
% 使用图像金字塔增强特征不变性
pyramidLevels = 3;
for level = 1:pyramidLevelsscale = 2^(-level);scaledImg = imresize(img, scale);% 提取多尺度特征并融合
end
2. 动态K值选择
% 交叉验证选择最佳K值
cv = cvpartition(size(trainFeatures,1),'KFold',5);
kValues = 1:5;
bestAcc = 0;for k = kValuescvAcc = crossval(@(X,Y) sum(predict(fitcknn(X,Y,k),Y) == Y)/numel(Y), ...trainFeatures, trainLabels, 'partition', cv);if cvAcc > bestAccbestK = k;bestAcc = cvAcc;end
end
disp(['最佳K值: ', num2str(bestK)]);
3. 特征空间优化
% 使用LDA替代PCA进行特征降维
[coeff, score, ~] = lda(trainFeatures, trainLabels);
projectedFeatures = score(:,1:10); % 降维到10维
三、工程实现建议
1. GPU加速
% 启用并行计算
parpool('local', 4);
gpuFeatures = gpuArray(trainFeatures);
2. 实时处理优化
% 视频流处理
vid = videoinput('winvideo', 1, 'YUY2_640x480');
vid.FramesPerTrigger = Inf;while isvalid(vid)frame = getsnapshot(vid);processed = preprocess(frame);feature = extractFeatures(processed);label = predict(mdl, feature);imshow(frame);title(['识别结果: ', num2str(label)]);drawnow;
end
四、典型应用场景
1. 门禁系统
% 实时人脸匹配
databaseFeatures = load('face_database.mat'); % 预存特征库
[minDist, idx] = min(pdist2(testFeature, databaseFeatures));
if minDist < 0.5disp(['欢迎 ', databaseLabels(idx)]);
elsedisp('访问拒绝');
end
2. 移动端部署
% 模型轻量化
compressedModel = compact(mdl);
save('knn_model.mat', 'compressedModel');
参考代码 采用模式识别算法在matlab中利用近邻法进行人脸识别 www.youwenfan.com/contentcni/65217.html
五、常见问题解决方案
1. 光照变化
% 自适应直方图均衡化
img = adapthisteq(grayImg, 'ClipLimit', 0.02);
2. 姿态变化
% 使用仿射变换对齐人脸
tform = estimateGeometricTransform(eyeCorners, faceCorners, 'affine');
alignedImg = imwarp(faceImg, tform);
3. 误识别问题
% 引入置信度阈值
[~, scores] = predict(mdl, testFeature);
if max(scores) < 0.7label = '未知';
end