Python: How can I reshape 3D Images (np array) to 1D and then reshape them back correctly to 3D?

10,362

Solution 1

If you are looking to create a 1D array, use .reshape(-1), which will create a linear version of you array. If you the use .reshape(32,32,3), this will create an array of 32, 32-by-3, arrays, which is the original format described. Using '-1' creates a linear array of the same size as the number of elements in the combined, nested array.

Solution 2

If M is (32 x 32 x 3), then .reshape(1,-1) will produce a 2d array (not 1d), of shape (1, 32*32*3). That can be reshaped back to (32,32,3) with the same sort of reshape statement.

But that's reshaping the input to and from But you haven't told us what the output of your Net is like. What shape does it have? How are you trying to reshape the output, and what is wrong with it?

Share:
10,362
costisst
Author by

costisst

Updated on June 23, 2022

Comments

  • costisst
    costisst almost 2 years

    I have RGB images (32 x 32 x 3) saved as 3D numpy arrays which I use as input for my Neural Net (using tensorflow). In order to use them as an input I reshape them to a 1D np array (1 x 3072) using reshape(1,-1). When I finish training my Net I want to reshape the output back, but using reshape(32,32,3) doesn't seem to provide the desired outcome.

    Is this the correct way to do it? How I can be sure that each datum will be back to the correct place?

  • costisst
    costisst almost 7 years
    What you said is correct. My question is: after I reshape the original array, will the values be at the same index they where before the linear reshape?
  • costisst
    costisst almost 7 years
    The output has the same shape as the input. So its (1,3072) and since my input is an image I want the output to be one as well. My reconstruction loss from the Net is small and when I tried to print the image again I get black background with lines of red green and blue. So I'm trying to see where I'm wrong. Either the NN or my reshape attemps.
  • Benedict Bunting
    Benedict Bunting almost 7 years
    As long as you use the same order of arguments, it should produce an array with the same structure as the original one.