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

Kuy*_*sea 22 python numpy machine-learning theano keras

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

我猜这可以完成工作,但它既丑陋又无法弄清楚如何扭转它以恢复原始图像.

Dan*_*ler 21

重新排序数据

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

np.rollaxis(imagesArray, 3, 1)  
Run Code Online (Sandbox Code Playgroud)

但是,如果您使用的是keras,则可能需要更改其配置或按层定义.如果你使用Keras,Theano不需要你.

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

配置keras

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

更改"image_data_format": "channels_last""channels_first"反之亦然,如你所愿.

通常,使用"channels_last"不太麻烦,因为大量的其他(非卷积)函数仅在最后一个轴上起作用.

在图层中定义渠道订单.

Keras文档有关于层参数,包括所有的信息data_format参数.

  • 我发现`np.moveaxis`更直观. (7认同)

cem*_*ara 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)
Run Code Online (Sandbox Code Playgroud)


小智 10

Using np.moveaxis is effective, but I have found that np.einsum is much faster.

\n\n
x = np.zeros((12,12,3))\n%timeit np.moveaxis(x,-1,0)\n#yields 7.46 \xc2\xb5s \xc2\xb1 312 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 100000 loops each)\n\n%timeit np.einsum('ijk->kij',x)\n#yields 1.11 \xc2\xb5s \xc2\xb1 31 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000000 loops each)\n
Run Code Online (Sandbox Code Playgroud)\n


Y0d*_*0da 8

如果您正在寻找最快的选项,请选择.transpose(...). 它甚至比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
Run Code Online (Sandbox Code Playgroud)