我需要帮助.UnicodeDecodeError:'utf-8'编解码器无法解码位置0的字节0xc1:无效的起始字节

问题描述

from __future__ import division
from __future__ import print_function
from __future__ import absolute_import

import os
import io
import pandas as pd
import tensorflow as tf

from PIL import Image
from object_detection.utils import dataset_util
from collections import namedtuple,OrderedDict

flags = tf.compat.v1.app.flags
flags.DEFINE_string('csv_input','','Path to the CSV input')
flags.DEFINE_string('output_path','Path to output TFRecord')
flags.DEFINE_string('image_dir','Path to images')
FLAGS = flags.FLAGS


# replace row_label with the name you annotated your images as
def class_text_to_int(row_label):
    if row_label == 'Masked':
        return 1
    elif row_label == 'No_Masked':
        return 2
    else :
        None


def split(df,group):
    data = namedtuple('data',['filename','object'])
    gb = df.groupby(group)
    return [data(filename,gb.get_group(x)) for filename,x in zip(gb.groups.keys(),gb.groups)]


def create_tf_example(group,path):
    with tf.io.gfile.GFile(os.path.join(path,'{}'.format(group.filename)),'rb') as fid:
        encoded_jpg = fid.read()
    encoded_jpg_io = io.BytesIO(encoded_jpg)
    image = Image.open(encoded_jpg_io)
    width,height = image.size

    filename = group.filename.encode('utf8')
    image_format = b'jpg'
    xmins = []
    xmaxs = []
    ymins = []
    ymaxs = []
    classes_text = []
    classes = []

    for index,row in group.object.iterrows():
        xmins.append(row['xmin'] / width)
        xmaxs.append(row['xmax'] / width)
        ymins.append(row['ymin'] / height)
        ymaxs.append(row['ymax'] / height)
        classes_text.append(row['class'].encode('utf8'))
        classes.append(class_text_to_int(row['class']))

    tf_example = tf.train.Example(features=tf.train.Features(feature={
        'image/height': dataset_util.int64_feature(height),'image/width': dataset_util.int64_feature(width),'image/filename': dataset_util.bytes_feature(filename),'image/source_id': dataset_util.bytes_feature(filename),'image/encoded': dataset_util.bytes_feature(encoded_jpg),'image/format': dataset_util.bytes_feature(image_format),'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),'image/object/class/text': dataset_util.bytes_list_feature(classes_text),'image/object/class/label': dataset_util.int64_list_feature(classes),}))
    return tf_example


def main(_):
    writer = tf.io.TFRecordWriter(FLAGS.output_path)
    path = os.path.join(FLAGS.image_dir)
    examples = pd.read_csv(FLAGS.csv_input)
    grouped = split(examples,'filename')
    for group in grouped:
        tf_example = create_tf_example(group,path)
        writer.write(tf_example.SerializeToString())

    writer.close()
    output_path = os.path.join(os.getcwd(),FLAGS.output_path)
    print('Successfully created the TFRecords: {}'.format(output_path))


if __name__ == '__main__':
    tf.compat.v1.app.run()

这是我的名为generate_tfrecord.py的代码。 我从github下载此代码作为我的第一个tensorflow tfrecord制作示例,但它出错了。 我是韩国人,发现我的计算机名为韩语时发生此错误。 但是,当我在cmd中键入“主机名”时,它返回了“ DESKTOP-7AU ~~~”,其中不包含韩文字母。

如果您对所需的代码或信息发表评论,我会尝试将其提供给您。

在我的图像-所有文件夹中,有764套img + xml文件,我已经运行了“ xml_to_csv.py”

此代码来自https://github.com/Bengemon825/TF_Object_Detection2020

解决方法

最简单的方法:您可以使用ASCII字符重命名主机名。 您可以搜索如何通过Google重命名主机名的问题。

此问题是由Python读取非Unicode字符引起的,无法通过utf-8解码。

,

我遇到了一个非常相似的问题,这是我的解决方法 - 我花了好几个小时才弄明白:

  1. 如果您是 Mac 用户,MacOS 在每个文件夹中都有组织 .DS_Store 格式文件的“隐形”文件夹。在遍历图像文件夹时,代码会遇到这些 utf-8 解码器无法解码的 .DS_Store 文件。删除它们是完全无害的,尽管它们实际上会重新出现,但您不必担心

  2. 所以你可以像this

    一样摆脱它们

OR(一旦发现问题,我更喜欢此选项):在您的代码中,您可以使用 if 语句显式绕过它们,该语句仅检查 .xml 文件或 .csv 文件或.txt 您在图像文件夹/目录中使用的任何文件。所以像:

path = 'path to folder containing your .xml files or .csv files or .txt files'

if '.xml' in str(path):
  1. 我还意识到,当人们直接按原样使用此 generate_tfrecord.py 时,许多人往往会忘记正确地明确调用他们的文件路径。使用 TensorFlow object_detection api 的 create_pascal_tf_record.py python 脚本的人也会发生这种情况。

例如,从上面的代码 flags.DEFINE_string('csv_input','','Path to the CSV input') 中,您需要用您的 csv 目录路径填写“ ”,而不是将其留空。例如flags.DEFINE_string('csv_input','add your csv directory path here','Path to the CSV input')。您必须对所有 flags.DEFINE_string 实例执行相同操作,否则如果您不想使用 flags.DEFINE_string 实例,则必须明确说明路径

我希望这对使用 Mac 并遇到各种 UnicodeDecodeError for TFRECORD 文件的人有所帮助。我不确定 Windows 用户是否遇到类似的情况。也可能有其他原因,但对我来说这恰好是原因

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...