Python 3.x Tensorflow:如何将float32转换为uint8

Python 3.x Tensorflow:如何将float32转换为uint8,python-3.x,tensorflow,Python 3.x,Tensorflow,代码如下: import tensorflow as tf raw_data = tf.gfile.FastGFile("0.png", "rb").read() image = tf.image.decode_png(raw_data) image = tf.image.resize_images(image, [28, 28], 0) with tf.Session() as sess: print(image) tf.cast(image, tf.uint8)

代码如下:

import tensorflow as tf

raw_data = tf.gfile.FastGFile("0.png", "rb").read()
image = tf.image.decode_png(raw_data)
image = tf.image.resize_images(image, [28, 28], 0)

with tf.Session() as sess:
    print(image)

    tf.cast(image, tf.uint8)
    print(image)

    tf.bitcast(tf.cast(image, dtype=tf.int8), tf.uint8)
    print(image)
Tensor("resize_images/Squeeze:0", shape=(28, 28, ?), dtype=float32)
Tensor("resize_images/Squeeze:0", shape=(28, 28, ?), dtype=float32)
Tensor("resize_images/Squeeze:0", shape=(28, 28, ?), dtype=float32)
输出:

import tensorflow as tf

raw_data = tf.gfile.FastGFile("0.png", "rb").read()
image = tf.image.decode_png(raw_data)
image = tf.image.resize_images(image, [28, 28], 0)

with tf.Session() as sess:
    print(image)

    tf.cast(image, tf.uint8)
    print(image)

    tf.bitcast(tf.cast(image, dtype=tf.int8), tf.uint8)
    print(image)
Tensor("resize_images/Squeeze:0", shape=(28, 28, ?), dtype=float32)
Tensor("resize_images/Squeeze:0", shape=(28, 28, ?), dtype=float32)
Tensor("resize_images/Squeeze:0", shape=(28, 28, ?), dtype=float32)

我想知道为什么我不能将float32转换为uint8,以及如何更正代码。

tf.cast不能就地转换数据;它返回新数据,您必须将其分配给变量或直接使用它

with tf.Session() as sess:
    print(image)

    image2 = tf.cast(image, tf.uint8)
    print(image2)

    image3 = tf.bitcast(tf.cast(image, dtype=tf.int8), tf.uint8)
    print(image3)

您似乎没有在会话中运行代码。例如,在尝试打印图像时,必须使用print(sess.run(image))。这同样适用于其他tf操作。