赞
踩
今天在处理图像时,发现输入图像的尺寸为(长、宽、通道数),需要改为(通道数、长、宽),起初打算使用np.reshape想当然的修改,但却发现已经修改了图像的内容。后来使用np.transpose修改成功。在此记录下两个函数的区别。
在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]])
上面就是把一个(2,4,3)形状的数组,先变成一维数组,然后在reshape成(3,2,4)的形状
>>> 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]]])
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。