【发布时间】:2020-06-30 20:32:14
【问题描述】:
我有一个形状为[None, 128, 128, n_classes] 的张量。这是一个one-hot tensor,其中最后一个索引包含多个类的分类值(总共有n_classes)。
在实践中,最后一个通道具有指示每个像素类别的二进制值:例如当一个像素在通道 C 中有 1 时,表示它属于 C 类;此像素在其他地方将有 0。
现在,我希望将这个单热张量转换为 RGB 图像,我想在 Tensorboard 上进行绘制。每个类都必须与不同的颜色相关联,以便于解释。
你知道怎么做吗?
谢谢,G。
编辑 2:
答案中添加了解决方案。
编辑 1:
我当前的实现(不工作):
def from_one_hot_to_rgb(incoming, palette=None):
""" Assign a different color to each class in the input tensor """
if palette is None:
palette = {
0: (0, 0, 0),
1: (31, 12, 33),
2: (13, 26, 33),
3: (21, 76, 22),
4: (22, 54, 66)
}
def _colorize(value):
return palette[value]
# from one-hot to grayscale:
cmap = tf.expand_dims(tf.argmax(incoming, axis=-1), axis=-1)
# flatten input tensor (pixels on the first axis):
B, W, H, C = get_shape(camp) # this returns batch_size, 128, 128, 5
cmap_flat = tf.reshape(cmap, shape=[B * W * H, C])
# assign a different color to each class:
cmap = tf.map_fn(lambda pixel:
tf.py_func(_colorize, inp=[pixel], Tout=tf.int64),
cmap_flat)
# back to original shape, but RGB output:
cmap = tf.reshape(cmap, shape=[B, W, H, 3])
return tf.cast(cmap, dtype=tf.float32)
【问题讨论】:
标签: python tensorflow one-hot-encoding