Julia: How to reshape an array while preserving the order?

Viewed 211

There is a similar question in Python, but I am asking about a Julia version.

I have a multidimensional array with shape img = (3, 64, 64), which represents an image with the first dimension being RGB. I want to use plt.imshow(img) to show the image in Jupyter Notebook, but plt.imshow takes an array with the shape (64, 64, 3). So,

is there any built-in function which can convert img without changing the order of pixels?

Notice: reshape(img, (64, 64, 3)) does not work. I have tried this and not get the original image.

I have written a nested for loop to illustrate what I want:

# Suppose img has been created
img_reshaped = zeros(size(img)[2], size(img)[3], size(img)[1])
for i in 1: size(img)[2]
    for j in 1: size(img)[3]
        for k in 1: size(img)[1]
            img_reshaped[i,j,k] = img[k,j,i]
        end
    end
end
plt.imshow(test_img)

The for loop above gives

enter image description here

while reshape(img, (64, 64, 3)) gives

enter image description here

which is not desired.

1 Answers

Expansion on the comment by @mcabbott

Short answer:

img_for_plot = permutedims(img, [2, 3, 1])

Here is the top of the help page on permutedims

help?> permutedims
search: permutedims permutedims! PermutedDimsArray

  permutedims(A::AbstractArray, perm)

  Permute the dimensions of array A. perm is a vector specifying a permutation of length ndims(A).

In your case it looks something like this:

julia> img = rand(1:256, 3, 6, 6)
3×6×6 Array{Int64,3}:
[:, :, 1] =
  42  193   60  250  215  145
  99  193  126   36  206  123
 210   28  190  234  186  139

[:, :, 2] =
  29  174  254  233  215  245
 247   64  254  133  124  254
 145  206   26   18  231  105

[:, :, 3] =
 198  120  191  181   43  209
  74  247  225  240   30  126
 231  163  104   24  237   18

[:, :, 4] =
 171   44   45  153   28   60
 145  180  220   82   47  132
 140   96   32  147  162   26

[:, :, 5] =
 246  180  221  136  158  111
 100  186   39  155  184  152
 112  237   11   60  222  171

[:, :, 6] =
 209  122  191   90  106   89
  17   91  163  117  168  215
 105  163  204  154  214  119

julia> size(img)
(3, 6, 6)

julia> img_for_plot = permutedims(img, [2, 3, 1])
6×6×3 Array{Int64,3}:
[:, :, 1] =
  42   29  198  171  246  209
 193  174  120   44  180  122
  60  254  191   45  221  191
 250  233  181  153  136   90
 215  215   43   28  158  106
 145  245  209   60  111   89

[:, :, 2] =
  99  247   74  145  100   17
 193   64  247  180  186   91
 126  254  225  220   39  163
  36  133  240   82  155  117
 206  124   30   47  184  168
 123  254  126  132  152  215

[:, :, 3] =
 210  145  231  140  112  105
  28  206  163   96  237  163
 190   26  104   32   11  204
 234   18   24  147   60  154
 186  231  237  162  222  214
 139  105   18   26  171  119

julia> size(img_for_plot)
(6, 6, 3)
Related