代码之家  ›  专栏  ›  技术社区  ›  Ericccccc

Tensorflow:如何将float32转换为uint8

  •  1
  • Ericccccc  · 技术社区  · 6 年前

    代码如下:

    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,以及如何更正代码。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Matthias Fripp    6 年前

    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)