2017-04-05 138 views
2

我试图从lmdbdataset中读取图像,对每个图像进行增强,然后将它们保存到另一个dataset中,以便在我的培训中使用。
这些图像轴在保存到lmdb dataset时最初更改为(3,32,32),所以为了增强它们,我必须将它们转换回它们的实际形状。
问题是每当我尝试使用matplotlibshow()方法或scipytoimage()显示它们时,它们都会显示图像的旋转版本。 因此,我们有:为什么转置一个numpy数组将它旋转90度?

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提供给我的扩展器时,我也会像前面的示例一样获得旋转的结果。
现在我不确定这是一个显示问题,还是实际的图像确实旋转了!
我该怎么办?

回答

6

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

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

通过转置阵列,可以反转尺寸的顺序:(RGB, X, Y)变为(Y, X, RGB)。这对matplotlib来说很好,因为颜色信息现在位于最后一个维度,但是X和Y也被交换了。如果您想保留X的顺序,Y,你可以告诉transpose to do so

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),这等同于(垂直,水平,颜色)或(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

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

+0

非常感谢,非常好的解释;) – Breeze