首页 > 解决方案 > 将值映射到 PNG 编码的 TensorFlow 张量

问题描述

我正在创建一个数据加载器,类似于:https ://github.com/tensorflow/models/blob/master/research/deeplab/datasets/build_cityscapes_data.py

在此脚本中,读取包含 uint8 标签的语义标签映射,编码为灰度 PNG 图像,然后将其序列化为 tfrecord 文件:

seg_data = tf.gfile.FastGFile(label_file, 'rb').read()

现在我想根据字典映射一个新的标签方案:

old_to_new = {"1": 30, "2": 50, "255": 15}

如果我有一个 numpy 数组,我可以执行以下操作:

seg_data_converted = seg_data.copy()
for old_label in old_to_new:
    seg_data_converted[seg_data==old_label] = old_to_new[old_label]

或使用更有效的函数来映射值。不幸的是,tf.gfile.FastGFile().read(n=-1)返回的输出

作为字符串请求的文件(或整个文件)的“n”个字节

如记录在:https ://www.tensorflow.org/versions/r1.0/api_docs/python/tf/gfile/FastGFile

如何将新值映射到张量并重新编码张量,以便我回到类似于 给出的表示tf.gfile.FastGFile().read()

第一种方法(不完整!):

  1. 解码使用:tf.image.decode_png()
  2. 映射值使用:tf.map_fn()
  3. 使用重新编码:tf.image.encode_png()

标签: pythontensorflow

解决方案


我认为这可以满足您的需求:

import tensorflow as tf

old_to_new = {"1": 30, "2": 50, "255": 15}
test_img_data = (b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x06\x00\x00'
                 b'\x00\x06\x08\x02\x00\x00\x00o\xaex\x1f\x00\x00\x00\x01sRGB'
                 b'\x00\xae\xce\x1c\xe9\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f'
                 b'\x0b\xfca\x05\x00\x00\x00\tpHYs\x00\x00\x0e\xc3\x00\x00\x0e'
                 b'\xc3\x01\xc7o\xa8d\x00\x00\x006IDAT\x18Wc\x04\x02\x06\x18'
                 b'\xf8\xf7\xef\x1f\x90d\x82p\x90\x01B\xc8\xcb\xcb\xcb\xc7\xc7'
                 b'\x07\xc8`\x02\xe9\x04\x03\x88\x04\x10021!\x14\xfe\xfd\xfb'
                 b'\x17Hb\x98\xc5\xc0\x00\x00\xe7i\x07\xd0\x19\xd3\x16\xa3'
                 b'\x00\x00\x00\x00IEND\xaeB`\x82')

# Input
image_data = tf.placeholder(tf.string, ())
# Decode
dtype = tf.uint8
png = tf.image.decode_png(image_data, channels=1, dtype=dtype)
# Mappings as vectors
old = tf.constant([int(k) for k in old_to_new.keys()], dtype=dtype)
new = tf.constant(list(old_to_new.values()), dtype=dtype)
# Compare matching values
mask = tf.equal(png, old)
# Mask to leave unmatched values untouched
mask_none = tf.reduce_all(~mask, axis=-1, keepdims=True)
# Compute result
replacements = new * tf.cast(mask, dtype)
png_new = png * tf.cast(mask_none, dtype) + tf.reduce_sum(replacements, axis=-1, keepdims=True)
# Encode
image_new_data = tf.image.encode_png(png_new)
# Test
with tf.Session() as sess:
    png_val, png_new_val = sess.run((png, png_new), feed_dict={image_data: test_img_data})
    print('Old PNG:')
    print(png_val[..., 0])
    print('New PNG:')
    print(png_new_val[..., 0])

输出:

Old PNG:
[[  1   1   1   1 255 255]
 [  1   1   1   1 255 255]
 [  1   1   1  75  75 255]
 [  2   2   2  75  75 255]
 [  2   2   2   2 255 255]
 [  2   2   2   2 255 255]]
New PNG:
[[30 30 30 30 15 15]
 [30 30 30 30 15 15]
 [30 30 30 75 75 15]
 [50 50 50 75 75 15]
 [50 50 50 50 15 15]
 [50 50 50 50 15 15]]

作为参考,这是测试图像(中的 PNG test_img_data):

测试图像

结果(由image_new_datawhen生成的 PNGtest_img_data作为输入):

测试结果图

它们很小以保持示例很小,但您可以使用图像编辑器缩放和检查值。


推荐阅读