0
votes

I have a set of color images in a folder which I read into a matrix in the following manner:

dirOutput = dir(fullfile('\ImageExample\images','*.jpg'));
fileNames = {dirOutput.name};
for k=1:length(fileNames)
    cd '\ImageExample\images'
    H=fileNames{k};
    S=im2double(imresize(imread(H),[20 20]));
    T=S(:);
    data=[data;T'];
end

Here, each image has been converted to a row vector of the matrix data. Now I do a set of operations and want to plot back each of the rows of data back as an image of size 20X20X3(rgb) with the matrix elements as uint8. What set of commands would help me do so? After processing, I get a matrix of double data type.

1
reshape, uint8, imshow, figure, help, imageDivakar

1 Answers

0
votes

Before we start, I would abolish storing each image as a single vector and use a cell array instead. That way, you could just index the cell array and it would give you an output image as a result and escape that transformation from row vector to image. However, my guess is that you're probably using some sort of minimization / machine learning framework where each image is a feature.

In any case, we are going to use the same cell array methodology here, and Divakar also pointed out what you should do. You used the (:) operator to transform each resized colour image into a single vector. To do the reverse operation, you need to use reshape. reshape takes in a 1D vector, and you specify the dimensions of the matrix you want and reshape will transform this 1D vector into the desired matrix of those desired dimensions. Bear in mind that the dimensions you specify must satisfy the total number of elements in your 1D vector.

As such, to read back in your images, run a for loop through all of the rows in your image, extract each row vector, run reshape, and store this into a cell array. You also need to use im2uint8 to convert the double image extracted per row, back into its original uint8 form. In other words:

numImages = size(data,1);
imageArray = cell(1,numImages);
for k = 1 : numImages
    T = data(k,:); %// Get row vector
    im = im2uint8(reshape(T, 20, 20, 3)); %// Reshape row vector into 20 x 20 x 3 matrix
    imageArray{k} = im;
end

If you want a one-liner solution (tip of the hat goes to Divakar), use arrayfun like so:

imageArray = arrayfun(@(x) im2uint8(reshape(data(x,:)), 20, 20, 3), 1:size(data,1), 'uni', 0);

Therefore, to access the kth image, simply do:

img = imageArray{k};

Good luck!