facial recognition in matlab

Facial recognition can be done in Matlab using several methods such as eigenfaces, fisherfaces, and local binary patterns histograms. Here is an example of how to do facial recognition using eigenfaces:

main.m
% Load the dataset
dataset = imageSet('path-to-dataset folder');
% Resize images to be the same size
imageSize = [200, 200];
inputImages = cell(1, dataset.Count);
for i=1:dataset.Count
    img = read(dataset, i);
    img = imresize(img, imageSize);
    inputImages{i} = rgb2gray(img);
end
% Create a matrix to store the flattened images
X = zeros(prod(imageSize), length(inputImages));
for i=1:length(inputImages)
    X(:,i) = inputImages{i}(:);
end
% Compute the average face
averageFace = mean(X,2);
% Subtract the mean from each image
X = X - repmat(averageFace, 1, length(inputImages));
% Compute the eigenvectors of the covariance matrix
[V, ~] = eig(X'*X);
% Take the largest eigenvectors as the principal components
numComponents = 50;
eigenvectors = X*V(:, end:-1:end-numComponents+1);
% Project each image onto the principal components
features = eigenvectors'*X;
% Test an unknown image
unknown = imread('path-to-unknown-image');
unknown = imresize(unknown, imageSize);
unknown = rgb2gray(unknown);
unknownFeatures = eigenvectors'*(unknown(:)-averageFace);
% Compute the Euclidean distance to each known image
distances = zeros(1, dataset.Count);
for i=1:dataset.Count
    distances(i) = norm(features(:,i)-unknownFeatures);
end
% Find the closest match
[~,index] = min(distances);
% Display the result
figure;
subplot(1,2,1); imshow(unknown); title('Unknown Image','FontSize',14);
subplot(1,2,2); imshow(read(dataset,index)); title('Matched Image','FontSize',14);
1475 chars
43 lines

This code loads a dataset of images, resizes them to the same size, flattens them into a matrix, computes the average face, subtracts the mean from each image, computes the eigenvectors of the covariance matrix, projects each image onto the principal components, and finally tests an unknown image by computing its Euclidean distance to each known image and finding the closest match.

gistlibby LogSnag