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

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

 

转载于:https://www.cnblogs.com/buxizhizhoum/p/8320043.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值