Skip to content
Advertisement

supposedly incorrect output np.reshape function

I have an array called “foto_dct” with shape (16,16,8,8) which means 16×16 matrices of 8×8.

When I print foto_dct[0,15], being the last matrix of the first row I get:

array([[0, 0, 0, 0, 0, 0, 0, 0],
   [0, 0, 0, 0, 0, 0, 0, 0],
   [0, 0, 0, 0, 0, 0, 0, 0],
   [0, 0, 0, 0, 0, 0, 0, 0],
   [0, 0, 0, 0, 0, 0, 0, 0],
   [0, 0, 0, 0, 0, 0, 0, 0],
   [0, 0, 0, 0, 0, 0, 0, 0],
   [0, 0, 0, 0, 0, 0, 0, 0]])

when i do foto_dct_big = np.reshape(foto_dct,(128,128)) and print foto_dct_big I get this:

[[  0   0   0 ...  49 148 245]
 [  0  16   0 ...  10   0   3]
 [  1   4   3 ... 148 137 128]
 ...
 [  0   0   0 ...   0   0   0]
 [  0   0   0 ...   0   0   0]
 [  0   0   0 ...   0   0   0]]

As you can see is the top righter corner( which is supposed to be the matrix above with all the zeros) is replaced with different values. This is only to prove that I indeed get different values, other parts of the matrix are false as well.

Why is this happening and how do I fix this?

Kind regards.

Advertisement

Answer

When using reshape, the order of the dimensions matter since that determines how the elements of the matrix will be read. As specified in the documentation, by default the last dimension is the one the fastest then follows the second to last and so on. So in your case when you do the reshape two 8×8 will be read first and reshaped into a row of your 128×128 matrix. For the read to be made in the correct order you first have to swap the dimensions to have the dimensions relating to the rows together (that is the rows of the 8×8 matrix and rows of the 16×16 matrix), same with the columns. You can do this with np.transpose.

I haven’t tested but I believe this should work

a = np.transpose(a, (0, 2, 1, 3)) # The new shape is (16, 8, 16, 8)
a = np.reshape(a, (128, 128))
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement