Val
Val

Reputation: 525

How to reconstruct an image using rgb values of all pixels in Matlab

I am trying to read an image using imread then, save the RGB values of all of the pixels in an array. And finally, be able to recreate this image using only the RGB values.

This is the for loop that saves all of the RGB values of each pixel.

A=imread('image.jpg');
N=2500; %the image dimensions are 50x50
i=1;
rgbValues = zeros(N, 3);
for x = 1:50
    for y = 1:50
        rgbValues(i,:) = A(x,y,:);
        i=i+1;
    end
end

Now, how am I able to recreate this image if I have all of the rgb values saved.

Upvotes: 0

Views: 1056

Answers (1)

Steve
Steve

Reputation: 4097

A direct way to do this is:

ny = 50;
nx = 50;
recreatedImage = zeros(ny,nx,3, 'uint8');
for ind = 1:3    
    recreatedImage(:,:, ind) =  ( reshape(rgbValues(:, ind), nx, ny))';
end

As Natan indicated, reshape will work also but you have to do this:

recreatedImage=reshape(rgbValues,[ny,nx,3]);

Which is, unfortunately, transposed so you will need to work it to get it rotated back up.

You might consider swapping your x and y values in your for loop so you iterate over all y and then all x values---because this is how MATLAB stores the data and you can change the above code to:

for ind = 1:3    
    recreatedImage(:,:, ind) =  ( reshape(rgbValues(:, ind), ny, nx));
end

(edit) and then the direct reshape works as well:

rgbValuesBacktoShape=reshape(rgbValues,[50,50,3]);

Upvotes: 1

Related Questions