MATLAB: How to perform automatic conversion of matrix dimensions of images in a way that it works for both rgb and grayscale ?

#face recognitioneigenfacesimage conversionimage dimensionspermutereshape

To perform face recognition, i have a train database with some images. The images in train database need to be pre-processed before they are used for comparison with the test image, which is the input image.
This is what i have done :
T = [];
for i = 1 : Train_Number
str = int2str(i);
str = strcat('\',str,'.jpg');
str = strcat(TrainDatabasePath,str);
img = imread(str);
img = rgb2gray(img);
img = imresize(img, [200 180]);
[irow icol] = size(img);
temp = reshape(img',irow*icol,1);
% temp = reshape(permute(double(img), [2,1,3]), irow*icol, 1);
T = [T temp]; % 'T' grows after each turn
end
This works fine when the train database contains only rgb images. But for grayscale images, it gives error related to dimensions.
How can i make it work for both rgb and grayscale ??

Best Answer

Some cleanup and an implicit conversion of grayscale images to pseudo-RGB:
nCol = 200;
nRow = 180;
% BUG?! T = nan(nCol * nRow, Train_Number); % Pre-allocate!!!
T = nan(nCol * nRow * 3, Train_Number); % Pre-allocate!!! [EDITED]
for i = 1 : Train_Number
filename = fullfile(TrainDatabasePath, sprintf('%d.jpg', i));
img = imread(filename);
if ndims(img) == 2 % Gray scale image:
img = double(cat(3, img, img, img)); % Pseudo RGB image
end
img = imresize(img, [nCol, nRow]);
temp = permute(img, [2,1,3]);
T(:, i) = temp(:);
end
But, I do not expect that the training of a face recognition system is efficient, when you feed it with RGB and gray-scale images. I'd prefer converting the RGB to gray scale instead.
img = rgb2gray(img);
Related Question