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

问题描述:tensorflow读取图片时出现错误UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid s

  • 系统版本:windows7 64位旗舰版 
  • tensorflow版本:tensorf 1.4.0
  • python版本:python 3.5.2
#coding:utf-8
import tensorflow as tf

import matplotlib.pyplot as plt

image =  tf.gfile.FastGFile('image/1.jpg','r').read()

with tf.Session() as sess:
    image = tf.image.decode_jpeg(image)
    print(image.eval())

    plt.imshow(image.eval())
    plt.show()

出现错误:File "E:/python_work/lab/6.py", line 6, in <module>
                 image =  tf.gfile.FastGFile('image/1.jpg','r').read()


问题分析:Python 3引入了用于打开文件的“r”和“rb”模式之间的区别。使用“r”模式将导致Python将文件内容解释为文本(在您的情况下(以及常见情况下)使用UTF-8编码),但是错误消息表明数据是二进制格式(可能是某种基于变量名的图像格式)。改变代码使用模式“rb”应该可以解决这个问题,并在两个版本的Python中工作:

image =  tf.gfile.FastGFile('image/1.jpg','rb').read()

参考:https://github.com/tensorflow/tensorflow/issues/11312

天上我才必有用,千金散尽还复来!
原文地址:https://www.cnblogs.com/lutaishi/p/13436327.html