I'm creating my dataset for a fine tuning task using tensorflow object detection api.
My directory structure is :
train/
-- imgs/
---- img1.jpg
-- ann/
---- img1.csv
where the csv, one per image, is label, x, y, w, h
I used this script to save the tfrecord:
import tensorflow as tf
from os import listdir
import os
from os.path import isfile, join
import csv
import json
from object_detection.utils import dataset_util
flags = tf.app.flags
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
FLAGS = flags.FLAGS
LABEL_DICT = {}
counter = 0
def create_tf_example(example):
# TODO(user): Populate the following variables from your example.
height = 404 # Image height
width = 720 # Image width
filename = example['path'].encode('utf-8').strip() # Filename of the image. Empty if image is not from file
with tf.gfile.GFile(example['path'], 'rb') as fid:
encoded_image_data = fid.read()
image_format = 'jpeg'.encode('utf-8').strip() # b'jpeg' or b'png'
xmins = [] # List of normalized left x coordinates in bounding box (1 per box)
xmaxs = [] # List of normalized right x coordinates in bounding box
# (1 per box)
ymins = [] # List of normalized top y coordinates in bounding box (1 per box)
ymaxs = [] # List of normalized bottom y coordinates in bounding box
# (1 per box)
classes_text = [] # List of string class name of bounding box (1 per box)
classes = [] # List of integer class id of bounding box (1 per box)
for box in example['boxes']:
#if box['occluded'] is False:
#print("adding box")
xmins.append(float(int(box['x']) / width))
xmaxs.append(float(int(box['w']) + int(box['x']) / width))
ymins.append(float(int(box['y']) / height))
ymaxs.append(float(int(box['h']) + int(box['y']) / height))
classes_text.append(box['label'].encode('utf-8'))
classes.append(int(LABEL_DICT[box['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_image_data),
'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 ex_info(img_path, ann_path):
boxes = []
head = ['label','x','y','w','h']
with open(ann_path, 'r') as csvfile:
annreader = csv.DictReader(csvfile, fieldnames=head)
for box in annreader:
boxes.append(box)
LABEL_DICT[box['label']] = LABEL_DICT.get(box['label'], len(LABEL_DICT) + 1)
ex = {
"path" : img_path,
"boxes" : boxes
}
return ex
def main(_):
writer = tf.python_io.TFRecordWriter(FLAGS.output_path)
# TODO(user): Write code to read in your dataset to examples variable
dataset_dir = "train"
ann_dir = join(dataset_dir, "ann")
imgs_dir = join(dataset_dir, "imgs")
labelDest = "tfTrain/data/labels_map.pbtxt"
imgs = [join(imgs_dir, f) for f in listdir(imgs_dir) if isfile(join(imgs_dir, f))]
anns = [join(ann_dir, os.path.basename(im).replace("jpg","csv")) for im in imgs]
for img,ann in zip(imgs,anns):
example = ex_info(img,ann)
#tf_example = create_tf_example(example)
#writer.write(tf_example.SerializeToString())
with open(labelDest, 'w', encoding='utf-8') as outL:
for name,key in LABEL_DICT.items():
outL.write("item { \n id: " + str(key) + "\n name: '" + name + "'\n}\n")
writer.close()
if __name__ == '__main__':
tf.app.run()
but then when I run the train script I got this error
python train.py --logtostderr --train_dir=./models/train --pipeline_config_path=faster_rcnn_resnet101_coc o.config
WARNING:tensorflow:From models/research/object_detection/trainer.py:257: create_global_step (from tensorflow.contrib.framewo rk.python.ops.variables) is deprecated and will be removed in a future version. Instructions for updating: Please switch to tf.train.create_global_step Traceback (most recent call last): File "models/research/object_detection/utils/label_map_util.py", line 135, in load_labelmap text_format.Merge(label_map_string, label_map) File "/home/user/anaconda3/envs/tf/lib/python3.6/site-packages/google/protobuf/text_format.py", line 525, in Merge descriptor_pool=descriptor_pool) File "/home/user/anaconda3/envs/tf/lib/python3.6/site-packages/google/protobuf/text_format.py", line 579, in MergeLines return parser.MergeLines(lines, message) File "/home/user/anaconda3/envs/tf/lib/python3.6/site-packages/google/protobuf/text_format.py", line 612, in MergeLines self._ParseOrMerge(lines, message) File "/home/user/anaconda3/envs/tf/lib/python3.6/site-packages/google/protobuf/text_format.py", line 627, in _ParseOrMerge self._MergeField(tokenizer, message) File "/home/user/anaconda3/envs/tf/lib/python3.6/site-packages/google/protobuf/text_format.py", line 727, in _MergeField merger(tokenizer, message, field) File "/home/user/anaconda3/envs/tf/lib/python3.6/site-packages/google/protobuf/text_format.py", line 815, in _MergeMessageField self._MergeField(tokenizer, sub_message) File "/home/user/anaconda3/envs/tf/lib/python3.6/site-packages/google/protobuf/text_format.py", line 695, in _MergeField (message_descriptor.full_name, name)) google.protobuf.text_format.ParseError: 23:20 : Message type "object_detection.protos.StringIntLabelMapItem" has no field named "s".During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "train.py", line 184, in <module> tf.app.run() File "/home/user/anaconda3/envs/tf/lib/python3.6/site-packages/tensorflow/python/platform/app.py",
line 126, in run _sys.exit(main(argv)) File "train.py", line 180, in main graph_hook_fn=graph_rewriter_fn) File "models/research/object_detection/trainer.py", line 264, in train train_config.prefetch_queue_capacity, data_augmentation_options) File "models/research/object_detection/trainer.py", line 59, in create_input_queue tensor_dict = create_tensor_dict_fn() File "train.py", line 121, in get_next dataset_builder.build(config)).get_next() File "models/research/object_detection/builders/dataset_builder.py", line 155, in build label_map_proto_file=label_map_proto_file) File "models/research/object_detection/data_decoders/tf_example_decoder.py", line 245, in init use_display_name) File "models/research/object_detection/utils/label_map_util.py", line 152, in get_label_map_dict label_map = load_labelmap(label_map_path) File "models/research/object_detection/utils/label_map_util.py", line 137, in load_labelmap label_map.ParseFromString(label_map_string) TypeError: a bytes-like object is required, not 'str'
I do not understand what's the problem. In the tfrecord? in the labels.pbtxt? or in the config file?