如何将numpy数组从(128,128,3)更改为(3,128,128)?

3

我正在读入一张图片,其大小为(128,128,3),但我有一个处理函数接收的是numpy数组(3,128,128)。我尝试使用.reshape(3,128,128),但这会改变原始图片。有没有一种方法可以改变numpy数组的形状而不改变图片?

img = cv2.imread("elephant copy.jpg") #(128,128,3)

这是我想要传递图像的函数:
def deprocess_image(x):
    x = np.subtract(x, x.mean(), out=x, casting="unsafe")
    x = np.divide(x, x.std()+1e-5, out=x, casting="unsafe")
    x = np.multiply(x, 0.1, out=x, casting="unsafe")

    x = np.add(x, 0.5, out=x, casting="unsafe")
    x = np.clip(x, 0, 1)

    x = np.multiply(x, 255, out=x, casting="unsafe")
    x = x.transpose((1, 2, 0))
    x = np.clip(x, 0, 255).astype('uint8')
    return x

该函数将梯度下降转换为图像,并应返回类似于以下内容的结果:enter image description here。欢迎提出任何建议,谢谢。

你的意思是图片已经改变了吗? - eyllanesc
我认为图像已经改变了,因为当我将其通过函数传递时(我只是将其添加到问题中),它返回完全黑色的图像,而不应该返回其他什么东西。 - matchifang
函数返回一个变量还是保存一张图片?用什么函数显示图片? - eyllanesc
它返回一个numpy数组,然后我使用scipy.misc.imsave保存。 - matchifang
似乎deprocess()函数中没有涉及到索引,因此数学运算和输入值应该是导致返回完全黑色图像的原因,而非索引。 - f5r5e5d
2个回答

4
你可以使用numpy.swapaxes来改变顺序,如下所示:
a = np.random.rand(128,128,3)
print(a.shape)  # (128, 128, 3)

b = np.swapaxes(a, 2,0)
print(b.shape)  # (3, 128, 128)

4

尝试使用transpose

您描述的形状为(128, 128, 3),您希望得到(3, 128, 128)
这可以通过以下两种方式实现
考虑数组a

a = np.random.rand(128, 128, 3)

case 1

# swap these two
#   ________
#  /        \
# (128, 128, 3)

a.transpose(2, 1, 0)
#           ^     ^
#           |     |
# make the last    \ make the first
# dimension the      dimension the
# first dimension    last dimension

case 2

# 3 goes to first spot
#   ________
#  /        \
# (128, 128, 3)
#  \____/ \__/
# each 128 shifts

#                 2nd dimension
#                 now last
a.transpose(2, 0, 1)
#           ^  ^
#           |   \
# make the last  \  make the first
# dimension the     dimension the
# first dimension   second dimension

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接