Matlab reshape back into original image

661 views Asked by At

I'm trying to reshape a multidimensional array into the original image. I have split an image of 512x512 pixels in sub-matrices of 8x8 pixels using the great solution that I found in this question:

sub_images = permute(reshape(permute(reshape(i_image, size(i_image, 1), n, []), [2 1 3]), n, m, []), [2 1 3]);

in this case n=m=8 and sub_images is an array of 8x8x4096. Now the problem is that I want to come back to the original image avoiding a for loops but I don't understand how to do it. I know that exist the functions colfiltor blockprocbut I can't use them. Any help is greatly appreciated!

2

There are 2 answers

0
ioums On BEST ANSWER

Just do the reverse of what you used to reshape the original array. The permute commands stay the same (switching the first and second dimension), while the reshape commands go back up to 512

reshaped_i_image = reshape(permute(reshape(permute(sub_images, [2 1 3]), 8, 512, []), [2 1 3]), 512, 512);
0
Divakar On

You can solve it with two reshape's and one permute -

out = reshape(permute(reshape(sub_images,n,m,512/n,512/m),[1 3 2 4]),512,[]);

Point to be noted here is that permute being costly, whenever possible must be avoided.


Listed next is a runtime test for the stated problem-size on the solution approaches listed so far -

i_image = rand(512,512);
n = 8; m = 8;
sub_images = permute(reshape(permute(reshape(i_image, size(i_image, 1), ...
                                   n, []), [2 1 3]), n, m, []), [2 1 3]);

func1 = @() reshape(permute(reshape(sub_images,n,m,512/n,512/m),...
                                                      [1 3 2 4]),512,[]);
func2 = @() reshape(permute(reshape(permute(sub_images, [2 1 3]), ...
                                        8, 512, []), [2 1 3]), 512, 512);


>> timeit(func1)
ans =
    0.0022201
>> timeit(func2)
ans =
    0.0046847