What is the correct way to change image channel ordering between channels first and channels last?

后端 未结 5 592
暗喜
暗喜 2021-02-02 07:28

I can not for the life of me figure out how to switch the image ordering. images are read in (x,x,3) format, theano requires it to be in (3,x,x) format. I tried changing the ord

5条回答
  •  余生分开走
    2021-02-02 07:56

    If you're looking at the fastest option, go for .transpose(...). It's even faster than 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
    

提交回复
热议问题