首页 > 解决方案 > 尝试开始训练时出现 UnicodeDecodeError

问题描述

我的研究小组的任务是训练一个使用 TensorFlow 检测汽车的网络。我们找到了一个我们认为看起来很简单的教程:
https
://towardsdatascience.com/creating-your-own-object-detector-ad69dda69c85 我们得到了图像,我们创建了.csv文件和 tfrecord 文件并尝试开始训练过程。这是我们得到的错误:

UnicodeDecodeError:“utf-8”编解码器无法解码位置 8 中的字节 0xbd:无效的起始字节

我们认为问题出在我们如何创建 tfrecord 文件,但也许有人可以为我们指明正确的方向。tfrecord 文件有 300MB 到 1.4GB 大,所以至少我们知道那里创建了一些东西。

我们的.csv文件是什么样子的(我们有大约 3500 张图像):

filename,label,xmin,ymin,xmax,ymax
SSDB00888.JPG,car,403.0,416.0,868.0,579.0
SSDB00889.JPG,car,46.0,419.0,303.0,539.0
SSDB00889.JPG,car,392.0,394.0,636.0,512.0
SSDB00889.JPG,car,819.0,367.0,1040.0,488.0
SSDB00890.JPG,car,553.0,419.0,1051.0,700.0

代码,我们要如何创建 tfrecord 文件。(当然,我们只是从教程中复制并进行了一些更改,因为我们的图像有不同类型的标签)。我们尝试在几个部分中更改代码,但没有真正改变。我们总是在训练开始时遇到错误,我们真的不知道怎么做。

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

import os
import io
import re

import pandas as pd
import tensorflow.compat.v1 as tf

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


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


# TO-DO replace this with label map
def class_text_to_int(row_label):
    if row_label == 'car':
        return 1
    elif row_label == 'pedestrian':
        return 2
    elif row_label == 'bicycle':
        return 3
    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.gfile.GFile(os.path.join(path, '{}'.format(re.sub('\s+', '', 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'
    # check if the image format is matching with your images.
    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['label'].encode('utf8'))
        classes.append(class_text_to_int(row['label']))

    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)
    }))
    return tf_example


def main(_):
        writer = tf.io.TFRecordWriter(FLAGS.output_path)
        path = os.path.join(os.getcwd(), FLAGS.img_path)
        examples = pd.read_csv(FLAGS.csv_input, sep=',', engine='python')
        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.app.run()

脚本被这样调用:python generate_tfrecord.py --csv_input=images\train_labels.csv --image_dir=images\train --output_path=train.record

我们如何解决错误?第一次 TensorFlow 太复杂了。

编辑:
我已经取得了一些进展。我发现我的 .tfrecords 文件似乎是'ansi'编码的而不是'utf-8'编码的。也许这就是引发错误的原因,但我不知道如何更改现有的 .tfrecord 文件或使用另一种编码制作新文件。

标签: pythontensorflowmachine-learningutf-8tfrecord

解决方案


面临同样的错误。问题出在用于训练的配置文件中(例如,faster_rcnn_inception_v2_coco.config)。我在参数中错误地指定了路径:“label_map_path”和“input_path”。


推荐阅读