我认为这可以满足您的需要:
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]]
供参考,这里是测试图像(test_img_data 中的 PNG):
以及结果(image_new_data 生成的 PNG,当test_img_data 作为输入时):
它们很小以保持示例较小,但您可以使用图像编辑器缩放和检查值。