【问题标题】:Julia: How to reshape an array while preserving the order?Julia:如何在保持顺序的同时重塑数组?
【发布时间】:2020-12-30 11:29:41
【问题描述】:

有一个similar question in Python,但我问的是 Julia 版本。

我有一个形状为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)) 给了

这是不希望的。

【问题讨论】:

  • 你在找permutedims,我想。
  • @mcabbott 你是对的!有用!谢谢!您能否将您的评论作为答案,以便我接受?

标签: arrays julia reshape


【解决方案1】:

扩展@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)

【讨论】:

    猜你喜欢
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    相关资源
    最近更新 更多