【问题标题】:Convert between NHWC and NCHW in TensorFlow在 TensorFlow 中转换 NHWC 和 NCHW
【发布时间】:2016-10-07 22:47:45
【问题描述】:

将张量从 NHWC 格式转换为 NCHW 格式(反之亦然)的最佳方法是什么?

是否有专门执行此操作的操作,或者我需要使用 split/concat 类型操作的某种组合?

【问题讨论】:

    标签: tensorflow


    【解决方案1】:

    您需要做的只是将维度从 NHWC 排列到 NCHW(或相反)。

    每个字母的含义可能有助于理解:

    • N:批次中的图像数量
    • H:图片的高度
    • W:图片的宽度
    • C:图像的通道数(例如:RGB 为 3,灰度为 1...)

    从 NHWC 到 NCHW

    图像形状为(N, H, W, C),我们希望输出的形状为(N, C, H, W)。因此,我们需要应用tf.transpose,并使用精心选择的排列perm

    返回的张量维度i将对应输入维度perm[i]

    perm[0] = 0  # output dimension 0 will be 'N', which was dimension 0 in the input
    perm[1] = 3  # output dimension 1 will be 'C', which was dimension 3 in the input
    perm[2] = 1  # output dimension 2 will be 'H', which was dimension 1 in the input
    perm[3] = 2  # output dimension 3 will be 'W', which was dimension 2 in the input
    

    在实践中:

    images_nhwc = tf.placeholder(tf.float32, [None, 200, 300, 3])  # input batch
    out = tf.transpose(images_nhwc, [0, 3, 1, 2])
    print(out.get_shape())  # the shape of out is [None, 3, 200, 300]
    

    从 NCHW 到 NHWC

    图像形状为(N, C, H, W),我们希望输出的形状为(N, H, W, C)。因此,我们需要使用tf.transpose 和精心选择的排列perm

    返回的张量维度i将对应输入维度perm[i]

    perm[0] = 0  # output dimension 0 will be 'N', which was dimension 0 in the input
    perm[1] = 2  # output dimension 1 will be 'H', which was dimension 2 in the input
    perm[2] = 3  # output dimension 2 will be 'W', which was dimension 3 in the input
    perm[3] = 1  # output dimension 3 will be 'C', which was dimension 1 in the input
    

    在实践中:

    images_nchw = tf.placeholder(tf.float32, [None, 3, 200, 300])  # input batch
    out = tf.transpose(images_nchw, [0, 2, 3, 1])
    print(out.get_shape())  # the shape of out is [None, 200, 300, 3]
    

    【讨论】:

    • 为了完整起见:解释为什么需要这些命令将是支持
    • @user3085931:你明白了
    • 另外,perm 是什么 - 或者它是如何定义的?
    • perm 是图像尺寸的排列,例如从 (N, H, W, C)(N, C, H, W)
    • 你在哪里使用xperm
    【解决方案2】:

    将“NCHW”转换为“NHWC”

    from keras import backend
    backend.set_image_data_format('channels_last') #channels_first for NCHW
    

    【讨论】:

    • 这不会做任何转换,它只会改变 Keras 解释数据的方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 2020-05-19
    • 2019-01-23
    • 1970-01-01
    相关资源
    最近更新 更多