MATLAB中的人脸识别

时间:2014-09-10 16:25:44

标签: matlab image-processing pca

我有一个错误,说:

  

订阅的分配维度不匹配。

Error in facerecognition (line 14) images(:, n) = img(:); 

有人可以帮忙吗?我写的代码如下:

input_dir = 'D:\C.S\FYP\Matlab Projects\DIP Applications\Face recognition\Faces\';

image_dims = [48, 64];

filenames = dir(fullfile(input_dir, '*.jpg'));

num_images = numel(filenames);

images = [];

for n = 1:num_images

    filename = fullfile(input_dir, filenames(n).name);
    img = imread(filename);
    if n == 1
        images = zeros(prod(image_dims), num_images);
    end
    images(:, n) = img(:);
end

% steps 1 and 2: find the mean image and the mean-shifted input images

mean_face = mean(images, 2);

shifted_images = images - repmat(mean_face, 1, num_images);


% steps 3 and 4: calculate the ordered eigenvectors and eigenvalues

[evectors, score, evalues] = princomp(images');


% step 5: only retain the top 'num_eigenfaces' eigenvectors (i.e. the principal components)

num_eigenfaces = 20;

evectors = evectors(:, 1:num_eigenfaces);


% step 6: project the images into the subspace to generate the feature vectors

features = evectors' * shifted_images;


% calculate the similarity of the input to each training image

feature_vec = evectors' * (input_image(:) - mean_face);

similarity_score = arrayfun(@(n) 1 / (1 + norm(features(:,n) - feature_vec)), 1:num_images);


% find the image with the highest similarity

[match_score, match_ix] = max(similarity_score);


% display the result

figure, imshow([input_image reshape(images(:,match_ix), image_dims)]);

title(sprintf('matches %s, score %f', filenames(match_ix).name, match_score))

2 个答案:

答案 0 :(得分:0)

错误表示images(:, n)的大小与img(:)的大小不同。你应该在该行上设置一个断点,并找出原因。

答案 1 :(得分:0)

由于您在开头指定的图像尺寸不一致而与您目录中的图像实际读入的尺寸相比,错误看起来是由于它造成的。当您在第一张图片中阅读时,我建议您在图像尺寸中动态读取。顺便说一下,如果您的所有图片在目录中都是相同的尺寸,这将。此外,假设您的所有图像都是灰度图像。但是,如果图像的大小不同,我可以放置代码,我们可以使用第一个图像作为参考尺寸。如果任何图像的尺寸与您读入的第一张图像不相等,我们会调整图像大小以使其符合此尺寸。

如果您有任何彩色图像,则在运行代码之前,您需要先将它们转换为灰度图像。因此,修改您的第一个for循环代码(您正在读取图像的位置),如下所示。这基本上就是您的代码,但在我修改过的任何地方,您都会在我放入的每行代码旁边看到%// NEW语句:

image_dims = []; %// NEW - Set to this instead of [48,64]

for n = 1:num_images

    filename = fullfile(input_dir, filenames(n).name);
    img = imread(filename);
    if size(img,3) == 3 %// NEW - Convert to gray scale if necessary
        img = rgb2gray(img); %// Use rgb2gray if colour
    end
    if n == 1
        image_dims = size(img); %// NEW - Read in image dimensions here
        images = zeros(prod(image_dims), num_images);
    else
        %// NEW - If the image read in is not the same dimensions
        %// as the first image read in, resize the image accordingly
        if size(img,1) ~= image_dims(1) || size(img,2) ~= image_dims(2)
            img = imresize(img, image_dims, 'bilinear');
        end
    end

    images(:, n) = img(:);
end