微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Julia:如何在保留顺序的同时重塑数组?

如何解决Julia:如何在保留顺序的同时重塑数组?

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

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

是否有任何内置函数可以转换img 而无需改变像素的顺序?

注意:reshape(img,(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,i]
        end
    end
end
plt.imshow(test_img)

上面的 for 循环给出

enter image description here

reshape(img,3)) 给予

enter image description here

这是不想要的。

解决方法

@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,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)

julia> img_for_plot = permutedims(img,1])
6×6×3 Array{Int64,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,3)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。