在TensorFlow中的NHWC和NCHW之间转换
tensorflow
6
0

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

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

参考资料:
Stack Overflow
收藏
评论
共 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(x, [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(x, [0, 2, 3, 1])
print(out.get_shape())  # the shape of out is [None, 200, 300, 3]
收藏
评论
新手导航
  • 社区规范
  • 提出问题
  • 进行投票
  • 个人资料
  • 优化问题
  • 回答问题

关于我们

常见问题

内容许可

联系我们

@2020 AskGo
京ICP备20001863号