'How to solve error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 106: invalid continuation byte in tensorflow

I need help to deal with an error... I try to create an object detection program with a tutorial made by lazy tech on Youtube. This tutorial use this repo on github https://github.com/Bengemon825/TF_Object_Detection2020

I have an error when I try to generate the tfrecord file for my train data and my test data. I run this on my terminal :

python generate_tfrecord.py --csv_input=data/train_labels.csv  --output_path=data/train.record

The the terminal returns this error :

File "C:\Users\Jules\AppData\Local\Programs\Python\Python39\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 79, in _preread_check
    self._read_buf = _pywrap_file_io.BufferedInputStream(
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 99: invalid continuation byte 

I don't understand why I have this error, because my csv files are in the good folder and the images too..

If someone knows how to solve this error it would help me a lot and allow me to continue the development of this project! I'm stuck on this for a week and I don't understand where this can come from... I already checked if the csv files were in utf-8 and yes they are...

The is the entire code of my generate_tfrecord.py file :

"""
Usage:
  # From tensorflow/models/
  # Create train data:
  python generate_tfrecord.py --csv_input=data/train_labels.csv  --output_path=train.record
  # Create test data:
  python generate_tfrecord.py --csv_input=data/test_labels.csv  --output_path=test.record
  python generate_tfrecord.py --csv_input=data/test_labels.csv  --output_path=data/test.record --image_dir=images/
"""

# taken from https://github.com/datitran/raccoon_dataset

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.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 == 'brassica':
        return 1
    elif row_label == 'deltoide':
        return 2
    elif row_label == 'marronnier':
        return 3
    elif row_label == 'paturin':
        return 4
    elif row_label == 'tremuloide':
        return 5
    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(str(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()


Solution 1:[1]

It is possible that the method you used to check the encoding is misleading and that the csv file includes data that does not conform to UTF-8. pd.read_csv supports specifying the encoding and from a similar question/response you could try pd.read_csv('file', encoding = "ISO-8859-1")

If that does not work, could you provide some information about how you verified the encoding? It may also help to open that file in something like Notepad or Notepad++, inspect what is going on at that position (99), and post the data in bytes.

Solution 2:[2]

I managed to solve the problem like this:

  1. overwrite csv file
  2. look for a non-existent photo in the csv file itself, I had exactly this
  3. update protobuff

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chubbs
Solution 2 Albert Gizatulin