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

标签 python numpy

我正在读取图像 (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

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

最佳答案

您可以使用 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)

关于python - 如何将 numpy 数组从 (128,128,3) 更改为 (3,128,128)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42014545/

相关文章:

python - 如何连接对象以在 Python 中创建或调用变量? - 编辑

python - Numpy np.where 多重条件

python - 3D 空间中最佳拟合平面的方向

python - 如何从大数据文件中查找两个选定列的总和?

python - 在 Python 中对多维数据样本应用非线性回归

python - 在 Django 应用程序中打开文件

python - numpy.where() 在这个例子中究竟是如何选择元素的?

python - 如何使用Elasticsearch库为python自动生成索引名?

python - 安装 pandas 包时出错 : no module named numpy

python - 尽可能快地旋转大型阵列