TensorFlow学习,'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

使用语句:

1 image_raw_data = tf.gfile.GFile("./picture.jpg", "r").read()

读取图像时报错如下:

1 UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

原因:

0x92 即 10010010,UTF8 中编码一个字符的第一个字节(start byte)只可能是 0xxxxxxx、110xxxxx、1110xxx、11110xxx……而后面的字节只可能是 10xxxxxx。也就是说 0x92 只能作为后面的字节,却出现在了第一个字节的位置。

出现这种问题绝大部分情况是因为文件不是 UTF8 编码的(例如,可能是 GBK 编码的),而系统默认采用 UTF8 解码。解决方法是改为对应的解码方式。

解决方案:

将“r”改为“rb”的形式,如下:

1 image_raw_data = tf.gfile.GFile("./picture.jpg", "rb").read()