当前位置:   article > 正文

Python Numpy中的reshape与transpose的用法以及区别_python中reshape和transpose的区别

python中reshape和transpose的区别

今天在处理图像时,发现输入图像的尺寸为(长、宽、通道数),需要改为(通道数、长、宽),起初打算使用np.reshape想当然的修改,但却发现已经修改了图像的内容。后来使用np.transpose修改成功。在此记录下两个函数的区别。

np.reshape

Numpy中,reshape的操作首先将多维数组转为一维向量,再按照转变后新数组的维度,截取拼成新的形状。一定不要用来处理图片信息!!!

下面希望将(2,4,3)形状的图像,转变成通道数3在前面的(3,2,4)的图像。

>>> import numpy as np
>>> x = np.random.rand(2,4,3)*10
>>> x_reshape = x.reshape((3,2,4))
>>> x
array([[[8.03765126, 4.39127424, 2.74543376],
        [9.37186554, 1.23974842, 0.7722333 ],
        [5.84788233, 5.74285694, 2.08277486],
        [4.12951592, 2.93530013, 6.5999786 ]],

       [[6.32425653, 8.86223448, 7.46397057],
        [2.16678125, 2.20945112, 1.25329685],
        [2.5462106 , 8.10238692, 3.1542975 ],
        [7.56363603, 9.06540176, 4.72479797]]])
>>> x_reshape
array([[[8.03765126, 4.39127424, 2.74543376, 9.37186554],
        [1.23974842, 0.7722333 , 5.84788233, 5.74285694]],

       [[2.08277486, 4.12951592, 2.93530013, 6.5999786 ],
        [6.32425653, 8.86223448, 7.46397057, 2.16678125]],

       [[2.20945112, 1.25329685, 2.5462106 , 8.10238692],
        [3.1542975 , 7.56363603, 9.06540176, 4.72479797]]])
#	相当于先转到1维再截取切分
>>> x.reshape(1, 24)
array([[8.03765126, 4.39127424, 2.74543376, 9.37186554, 1.23974842,
        0.7722333 , 5.84788233, 5.74285694, 2.08277486, 4.12951592,
        2.93530013, 6.5999786 , 6.32425653, 8.86223448, 7.46397057,
        2.16678125, 2.20945112, 1.25329685, 2.5462106 , 8.10238692,
        3.1542975 , 7.56363603, 9.06540176, 4.72479797]])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

上面就是把一个(2,4,3)形状的数组,先变成一维数组,然后在reshape成(3,2,4)的形状

np.transpose
>>> x_transpose = x.transpose(2,0,1)
>>> x
array([[[8.03765126, 4.39127424, 2.74543376],
        [9.37186554, 1.23974842, 0.7722333 ],
        [5.84788233, 5.74285694, 2.08277486],
        [4.12951592, 2.93530013, 6.5999786 ]],

       [[6.32425653, 8.86223448, 7.46397057],
        [2.16678125, 2.20945112, 1.25329685],
        [2.5462106 , 8.10238692, 3.1542975 ],
        [7.56363603, 9.06540176, 4.72479797]]])
>>> x_transpose
array([[[8.03765126, 9.37186554, 5.84788233, 4.12951592],
        [6.32425653, 2.16678125, 2.5462106 , 7.56363603]],

       [[4.39127424, 1.23974842, 5.74285694, 2.93530013],
        [8.86223448, 2.20945112, 8.10238692, 9.06540176]],

       [[2.74543376, 0.7722333 , 2.08277486, 6.5999786 ],
        [7.46397057, 1.25329685, 3.1542975 , 4.72479797]]])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/154116?site
推荐阅读
相关标签
  

闽ICP备14008679号