python - 为什么转置一个 numpy 数组将它旋转 90 度?

标签 python numpy matplotlib scipy caffe

我正在尝试从 lmdb dataset 中读取图像,对每个图像进行扩充,然后将它们保存到另一个 dataset 中以供我使用培训。
这些图像轴最初在保存到 lmdb 数据集 时更改为 (3,32,32),因此为了增强它们,我不得不将它们转置回去变成它们的实际形状。
问题是每当我尝试使用 matplotlibshow() 方法或 scipytoimage(),它们显示图像的旋转版本。 所以我们有:

img_set = np.transpose(data_train,(0,3,2,1))
#trying to display an image using pyplot, makes it look like this:  
plt.subplot(1,2,1)
plt.imshow(img_set[0])

enter image description here

使用 toimage 显示相同的图像:

enter image description here

现在,如果我不转置 data_trainpyplotshow() 会在 toimage() 很好地显示图像:
enter image description here

这里发生了什么?
当我将转置的 data_train 提供给我的增强器时,我也会像前面的示例一样旋转结果。
现在我不确定这是显示问题,还是实际图像确实旋转了!
我应该怎么办 ?

最佳答案

首先,仔细观察。转置阵列不旋转,而是在对角线上镜像(即交换 X 和 Y 轴)。

原始形状是(3,32,32),我解释为(RGB, X, Y)。但是,imshow 需要一个形状为 MxNx3 的数组 - 颜色信息必须位于最后一个维度。

通过转置数组,您可以反转维度的顺序:(RGB, X, Y) 变为 (Y, X, RGB)。这对 matplotlib 很好,因为颜色信息现在在最后一个维度中,但 X 和 Y 也被交换了。如果您想保留 X、Y 的顺序,您可以告诉 transpose 这样做:

import numpy as np

img = np.zeros((3, 32, 64))  # non-square image for illustration

print(img.shape)  # (3, 32, 64)
print(np.transpose(img).shape)  # (64, 32, 3)
print(np.transpose(img, [1, 2, 0]).shape)  # (32, 64, 3)

当使用 imshow 显示图像时,请注意以下陷阱:

  1. 它将图像视为矩阵,因此数组的维度被解释为 (ROW, COLUMN, RGB),相当于 (VERTICAL, HORIZONTAL, COLOR) 或 (Y, X, RGB) .

  2. 它改变了 y 轴的方向,所以左上角是 img[0, 0]。这与 matplotlib 的常规坐标系不同,其中 (0, 0) 是左下角。

例子:

import matplotlib.pyplot as plt

img = np.zeros((32, 64, 3))
img[1, 1] = [1, 1, 1]  # marking the upper right corner white

plt.imshow(img)

enter image description here

请注意,较小的第一维对应于图像的垂直方向。

关于python - 为什么转置一个 numpy 数组将它旋转 90 度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43227040/

相关文章:

python - Django ValueError 位于/admin/

python - Fortran:以 Python 方式使用数组:派生类型、派生类型迭代

python - 字符串的常量部分

python - 不展平的排序矩阵,numpy

python - 如何从 csv 文件中读取日期/时间字段并在 python 中相应地绘制图形

python - 写入Python切片?

python - 在python中获取每个月的年份

numpy - scipy.sparse.linalg : what's the difference between splu and factorized?

python - 如何对seaborn relplot的轴使用对数刻度?

python - 圆形变成椭圆形 - 在 Python 中设置长宽比