zoukankan      html  css  js  c++  java
  • tensorflow UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

    tensorflow读取图像出现错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    import matplotlib.pyplot as plt
    import tensorflow as tf
    
    
    filename = "/home/zzz/1-Work/Documents/2-Codes/learning/tf/17flowers/jpg/0/image_0001.jpg"
    image_raw_data = tf.gfile.FastGFile(filename, "r").read()  # 问题出在这里,mode应该为“rb”而不是“r”
    
    with tf.Session() as sess:
        img_data = tf.image.decode_jpeg(image_raw_data)
        tmp = img_data.eval()
        print(tmp)
        plt.imshow(tmp)
        plt.show()
        img_data = tf.image.convert_image_dtype(img_data, dtype=tf.uint8)
        encoded_img = tf.image.encode_jpeg(img_data)
        with tf.gfile.GFile("/home/zzz/tf_tmp", "wb") as f:
            f.write(encoded_img.eval())

    原因:在

    image_raw_data = tf.gfile.FastGFile(filename, "r").read()

    这一行,读取的时候读取方式应该是“rb”,在读取模式只使用“r”的时候,python试图将一个byte-array转成utf-8字符串,这样python就会遇到utf-8的非法字符: 0xff in position 0,遇到这种情况时,可以将读取方式改为“rb”,这样在读取数据的时候,会将数据按照二进制读取,就不会有上述的解码问题。

    ps:引起这个问题的另一个原因可能是所要读取的数据是按照utf-16编码的,在这种情况下,可以加关键字参数,encoding=“utf-16”解决。

    ref: https://stackoverflow.com/questions/42339876/error-unicodedecodeerror-utf-8-codec-cant-decode-byte-0xff-in-position-0-in

  • 相关阅读:
    poj2955(区间dp)
    poj3280(区间dp)
    poj1651(区间dp)
    hdu5001(概率dp)
    hdu4389(数位dp)
    hdu4352(数位dp)
    CF 148D(概率dp)
    zoj3329(概率dp)
    POJ1028 Web Navigation
    POJ1027 The Same Game
  • 原文地址:https://www.cnblogs.com/buxizhizhoum/p/8320043.html
Copyright © 2011-2022 走看看