Skip to main content
 首页 » 编程设计

python之tensorflow: "tf.gfile.GFile"中有问题, "' utf- 8' codec can' t 解码...”

2024年08月19日31duanxz

当我运行我的代码时,我得到这样的错误:

File "data2record.py", line 120, in <module> 
    run() 
  File "data2record.py", line 114, in run 
    image_data, shape, bbox, label ,imname= _processing_image(wordbb, imname,coder) 
  File "data2record.py", line 64, in _processing_image 
    image_data = tf.gfile.GFile(FLAGS.datasets + imname, 'r').read() 
  File "/home/tian/.local/lib/python3.5/site-packages/tensorflow/python/lib/io/file_io.py", line 125, in read 
    pywrap_tensorflow.ReadFromStream(self._read_buf, length, status)) 
  File "/home/tian/.local/lib/python3.5/site-packages/tensorflow/python/lib/io/file_io.py", line 93, in _prepare_value 
    return compat.as_str_any(val) 
  File "/home/tian/.local/lib/python3.5/site-packages/tensorflow/python/util/compat.py", line 106, in as_str_any 
    return as_str(value) 
  File "/home/tian/.local/lib/python3.5/site-packages/tensorflow/python/util/compat.py", line 84, in as_text 
    return bytes_or_text.decode(encoding) 
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte 

我代码中的错误行是:

... 
image_data = tf.gfile.GFile(FLAGS.datasets + imname, 'r').read() 
image = coder.decode_jpeg(image_data) 
... 

我的tensorflow是1.3,python是3.5,而这段代码在tensorflow 1.0,python 2.7都可以跑,为什么不能在tensorflow 1.3,python 3.5跑? 代码在datasets/data2record.py中:https://github.com/xiaodiu2010/TextBoxes-TensorFlow 有人可以帮助我吗?

请您参考如下方法:

如错误所述,因为它试图将文件数据解码为 un​​icode 但失败了。

改变行:

image_data = tf.gfile.GFile(FLAGS.datasets + imname, 'r').read()

到:

image_data = tf.gfile.GFile(FLAGS.datasets + imname, 'rb').read()

以二进制方式读取文件。它在 Py2 中工作,因为默认情况下 str 是一个字节字符串,而在 Py3 中它是一个 unicode 字符串,因此在以文本模式读取文件时需要解码。