Python 如何将numpy数组从(128128,3)更改为(3128128)?

Python 如何将numpy数组从(128128,3)更改为(3128128)?,python,numpy,Python,Numpy,我正在读取一个图像,它是(128128,3),但我有一个处理函数,它接受numpy数组(3128128)。我尝试使用.reformate(3128128),但图像与原始图像不同。有没有一种方法可以在不改变图像的情况下改变numpy阵列的形状 img = cv2.imread("elephant copy.jpg") #(128,128,3) 这是我要将图像传递给的函数: def deprocess_image(x): x = np.subtract(x, x.mean(), out=x

我正在读取一个图像,它是(128128,3),但我有一个处理函数,它接受numpy数组(3128128)。我尝试使用
.reformate(3128128)
,但图像与原始图像不同。有没有一种方法可以在不改变图像的情况下改变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
该函数将渐变下降转换为图像,并返回如下内容:

非常感谢您的任何建议。谢谢。

您可以使用以下方式更改订单:

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)

尝试使用
转置

您将形状描述为
(128,128,3)
,并且希望
(3,128,128)

这可以通过两种方式之一发生
考虑数组<代码> A<代码> < /P>
a = np.random.rand(128, 128, 3)
案例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
# 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
案例2

# 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
# 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

图像发生了变化是什么意思?我认为图像发生了变化,因为当我将其传递给函数(我刚刚将其添加到问题中)时,它会在返回其他内容时返回一个完全黑色的图像。函数是返回变量还是保存图像?,用什么函数显示图像?它返回一个numpy数组,然后我使用scipy.misc.imsave保存它。deprocess()中的任何东西看起来都不一样取决于索引,因此数学和输入值负责返回一个完全黑色的图像,而不是索引