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


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM