首页 > 解决方案 > Julia:如何在保持顺序的同时重塑数组?

问题描述

Python 中有一个类似的问题,但我问的是 Julia 版本。

我有一个 shape 的多维数组img = (3, 64, 64),它表示第一维为 RGB 的图像。我想用来plt.imshow(img)在 Jupyter Notebook 中显示图像,但plt.imshow需要一个形状为(64, 64, 3). 所以,

是否有任何内置函数可以在img 改变像素顺序的情况下进行转换?

注意:reshape(img, (64, 64, 3))不起作用。我已经尝试过了,但没有得到原始图像。

我写了一个嵌套for循环来说明我想要什么:

# 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)

上面的for循环给出

在此处输入图像描述

reshape(img, (64, 64, 3))

在此处输入图像描述

这是不希望的。

标签: arraysjuliareshape

解决方案


@mcabbott 对评论的扩展

简短的回答:

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

这是帮助页面的顶部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).

在您的情况下,它看起来像这样:

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)

推荐阅读