首先更改频道和频道之间的图像频道顺序的正确方法是什么?

时间:2017-05-07 09:05:20

标签: python numpy machine-learning keras theano

我不能为我的生活弄清楚如何切换图像排序。图像以(x,x,3)格式读取,theano要求它为(3,x,x)格式。我尝试用改变顺序 numpy.array([img[:,:,i] for i in range(3)])

我猜这个工作已经完成,但它既丑陋又无法弄清楚如何将其反转以恢复原始图像。

5 个答案:

答案 0 :(得分:20)

重新排序数据

您可以使用numpy.rollaxis将轴3滚动到位置1(考虑到批次大小为维度0)。

np.rollaxis(imagesArray, 3, 1)  

但是,如果您正在使用keras,则可能需要更改其配置或按层定义。如果你正在使用Keras,Theano并不需要你的任何东西。

Keras可以首先配置通道,也可以配置最后通道,除了允许您在每个单独的层中定义它,因此您不必更改数据。

配置keras

找到keras.json文件并进行更改。该文件通常安装在C:\Users\yourusername\.keras~/.keras中,具体取决于您的操作系统。

根据需要将"image_data_format": "channels_last"更改为"channels_first",反之亦然。

通常,使用" channels_last"由于大量其他(非卷积)函数仅在最后一个轴上起作用,因此不那么麻烦。

在图层中定义渠道订单。

Keras documentation包含有关图层参数的所有信息,包括data_format参数。

答案 1 :(得分:11)

我同意@Qualia的评论,np.moveaxis(a, source, destination)更容易理解。这样做了:

x = np.zeros((12, 12, 3))
x.shape
#yields: 
(12, 12, 3)

x = np.moveaxis(x, -1, 0)
x.shape
#yields: 
(3, 12, 12)

答案 2 :(得分:3)

如果您正在寻找最快的选择,请选择np.einsum。它甚至比img = np.random.random((1000, 1000, 3)) img.shape # (1000, 1000, 3) %timeit img.transpose(2, 0, 1) # 385 ns ± 1.11 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) %timeit np.rollaxis(img, -1, 0) # 2.7 µs ± 50.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) %timeit np.einsum('ijk->kij', img) # 2.75 µs ± 31.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) %timeit np.moveaxis(img, -1, 0) # 7.26 µs ± 57.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) np.allclose(img.transpose(2, 0, 1), np.einsum('ijk->kij', img)) # True np.allclose(img.transpose(2, 0, 1), np.moveaxis(img, -1, 0)) # True np.allclose(img.transpose(2, 0, 1), np.rollaxis(img,-1, 0)) # True 还快。

public interface Byteable<T> {
    byte[] toBytes();
    Builder<T> builder();

    interface Builder<T> {
        T fromBytes(byte[] bytes);
    }
}

答案 3 :(得分:2)

使用np.moveaxis是有效的,但是我发现np.einsum更快。

x = np.zeros((12,12,3))
%timeit np.moveaxis(x,-1,0)
#yields 7.46 µs ± 312 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit np.einsum('ijk->kij',x)
#yields 1.11 µs ± 31 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

答案 4 :(得分:-1)

x = np.zeros((12, 12, 3))
y = np.rollaxis(x, 2, 0)
y.shape

(3, 12, 12)