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

今天在跑跑代码时,遇到了标题的问题,然后网上查了下,在此处:

http://www.cnblogs.com/Qt-Chao/p/7474360.html 刚刚好讲解了解决该问题的办法,这里当作一个笔记,记录下来。

我使用pycharm  Python3.6  TensorFlow 1.3  的开发环境

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

在是使用Tensorflow读取图片文件的情况下,会出现这个报错

代码如下

#coding = utf-8
import tensorflow as tf
import matplotlib.pyplot as plt

image = tf.gfile.FastGFile("C:\\Users\\xiaoj\\Desktop\\MNIST_data\\timg.jpg","r").read()

with tf.Session() as sess:
    imag_after_decode = tf.image.decode_jpeg(image)
    print(imag_after_decode.eval())
    plt.imshow(imag_after_decode.eval())
    plt.show()

报错如下:

C:\Users\xiaoj\AppData\Local\Programs\Python\Python36\python.exe C:/Users/xiaoj/PycharmProjects/Exercise/tensorE4.py
Traceback (most recent call last):
  File "C:/Users/xiaoj/PycharmProjects/Exercise/tensorE4.py", line 5, in <module>
    image = tf.gfile.FastGFile("C:\\Users\\xiaoj\\Desktop\\MNIST_data\\timg.jpg","r").read()
  File "C:\Users\xiaoj\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 127, in read
    pywrap_tensorflow.ReadFromStream(self._read_buf, length, status))
  File "C:\Users\xiaoj\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 95, in _prepare_value
    return compat.as_str_any(val)
  File "C:\Users\xiaoj\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\util\compat.py", line 113, in as_str_any
    return as_str(value)
  File "C:\Users\xiaoj\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\util\compat.py", line 86, in as_text
    return bytes_or_text.decode(encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

度娘没有查找到结果,Google上找到了相应的解决方案:

#coding = utf-8
import tensorflow as tf
import matplotlib.pyplot as plt

image = tf.gfile.FastGFile("C:\\Users\\xiaoj\\Desktop\\MNIST_data\\timg.jpg","rb").read()

with tf.Session() as sess:
    imag_after_decode = tf.image.decode_jpeg(image)
    print(imag_after_decode.eval())
    plt.imshow(imag_after_decode.eval())
    plt.show()

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