Creating tf_record files for own data set - how?
Hello, I am currently working with the Tensorflow Object Detection API but I am struggling how to convert an image folder in the corresponding tfrecords format in order to work with it.
I read the tutorial https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/using_your_own_dataset.md (Conversion Script Outline)
main():
# TODO(user): Write code to read in your dataset to examples variable
It is unclear how I have to laod my data in the TODO section.
My data is organized as following:
|-- Data
|-- [MyDataSetName]
|-- Images
|-- [.png] Image Files
|-- Annotations
|-- [.txt] Annotation FIles: (x1, y1, x2, y2, label ID)
|-- Names
|-- train.txt (List of training data filenames)
|-- test.txt (List of testing data filenames)
|-- valid.txt (List of validation data filenames)
So, how should i load the data in order to obtain a correct tfrecord file? How should be xmin, xmax and so be organized, as a list containing all coordinates, e.g. of the left upper corner, for each bounding box?
Second, I have to specify encoded_image_data but I am not sure what is meant by this. Could you please explain it?
Thanks a lot in advance
An easier thing to do would be to structure your dataset on pascal_voc format and use dataset_tools/create_pascal_tf_record.py script to generate your tf.record file.
Hi @RomailM That is a good idea, thanks. However, the create_pascal_tf_record.py as well as the create_kitti_tf_record.py use further information like difficult_obj, truncated, poses or 3D boxes and those information I do not have. Therefore, I cannot use these python files even if it could be easy.
So, I need to use the python file from https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/using_your_own_dataset.md#conversion-script-outline-conversion-script-outline and I am still not sure how to use it properly.
- How should be the bbox coordinates be organized?
- What should the variable
encoded_image_datacontain? - What should
classes = [] # List of integer class id of bounding box (1 per box)contain? A unique ID or whataver=
I used generate_tf_record script from this repo. https://github.com/datitran/raccoon_dataset. He has a very nice guide here https://towardsdatascience.com/how-to-train-your-own-object-detector-with-tensorflows-object-detector-api-bec72ecfe1d9
@RomailM Thanks for the links. However, the guide does not contain any information about the issues I have, mentioned in my last comment...
@RomailM I tried to figure out how to write the required variables but I end up that I create an Image file and not a Binary file. Any ideas why it is in the wrong format?
@RomailM Here the code: My data is organized as drescibed above
import tensorflow as tf
from object_detection.utils import dataset_util
import os, glob
from PIL import Image
flags = tf.app.flags
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
flags.DEFINE_string('anno_path', '', 'Path to Annotation Files')
flags.DEFINE_string('image_path', '', 'Path to Image Files')
FLAGS = flags.FLAGS
def create_tf_example(currentName, anno_path, image_path):
currentNameSplit = currentName.split('.')[0]
currentImageName = currentNameSplit + '.png'
with tf.gfile.GFile(os.path.join(image_path, '{}'.format(currentImageName)), 'rb') as fid:
encoded_image_data = fid.read()
image = Image.open(image_path + currentImageName)
width, height = image.size
filename = currentNameSplit.encode('utf8')
image_format = b'png'
with open(anno_path + currentName) as file:
lines = file.readlines()
xmins = []
xmaxs = []
ymins = []
ymaxs = []
classes_text = []
classes = []
for li in range(len(lines)):
print('Lines[li]: {}'.format(lines[li]))
xmins.append(float(lines[li].split()[0]) / width)
xmaxs.append(float(lines[li].split()[2]) / width)
ymins.append(float(lines[li].split()[1]) / height)
ymaxs.append(float(lines[li].split()[3]) / height)
classID = lines[li].split()[4]
if int(classID) == 0:
className = 'Car'
classes_text.append(className.encode('utf8'))
classID = 0
classes.append(classID)
elif int(classID) == 1:
className = 'Person'
classes_text.append(className.encode('utf8'))
classID = 1
classes.append(classID)
elif int(classID) == 2:
className = 'Traffic Sign'
classID = 2
classes_text.append(className.encode('utf8'))
classes.append(classID)
else:
print('Error with Image Annotations in {}'. format(currentName))
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 main(_):
writer = tf.python_io.TFRecordWriter(FLAGS.output_path)
allAnnotationFiles = []
os.chdir(FLAGS.anno_path)
for file in sorted(glob.glob("*.{}".format('txt'))):
allAnnotationFiles.append(file)
for currentName in allAnnotationFiles:
tf_example = create_tf_example(currentName, FLAGS.anno_path, FLAGS.image_path)
writer.write(tf_example.SerializeToString())
writer.close()
if __name__ == '__main__':
tf.app.run()
install AOCR using this command: pip install aocr
after that use this command: aocr dataset annotation-training.txt training.tfrecords
Provide annotation-training.txt where each line should contain image path and labels separated by space.
@RomailM Here the code: My data is organized as drescibed above import tensorflow as tf
from object_detection.utils import dataset_util
import os, glob from PIL import Image
flags = tf.app.flags flags.DEFINE_string('output_path', '', 'Path to output TFRecord') flags.DEFINE_string('anno_path', '', 'Path to Annotation Files') flags.DEFINE_string('image_path', '', 'Path to Image Files')
FLAGS = flags.FLAGS
def create_tf_example(currentName, anno_path, image_path):
currentNameSplit = currentName.split('.')[0] currentImageName = currentNameSplit + '.png' with tf.gfile.GFile(os.path.join(image_path, '{}'.format(currentImageName)), 'rb') as fid: encoded_image_data = fid.read() image = Image.open(image_path + currentImageName) width, height = image.size filename = currentNameSplit.encode('utf8') image_format = b'png' with open(anno_path + currentName) as file: lines = file.readlines() xmins = [] xmaxs = [] ymins = [] ymaxs = [] classes_text = [] classes = [] for li in range(len(lines)): print('Lines[li]: {}'.format(lines[li])) xmins.append(float(lines[li].split()[0]) / width) xmaxs.append(float(lines[li].split()[2]) / width) ymins.append(float(lines[li].split()[1]) / height) ymaxs.append(float(lines[li].split()[3]) / height) classID = lines[li].split()[4] if int(classID) == 0: className = 'Car' classes_text.append(className.encode('utf8')) classID = 0 classes.append(classID) elif int(classID) == 1: className = 'Person' classes_text.append(className.encode('utf8')) classID = 1 classes.append(classID) elif int(classID) == 2: className = 'Traffic Sign' classID = 2 classes_text.append(className.encode('utf8')) classes.append(classID) else: print('Error with Image Annotations in {}'. format(currentName)) 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_exampledef main(_): writer = tf.python_io.TFRecordWriter(FLAGS.output_path)
allAnnotationFiles = [] os.chdir(FLAGS.anno_path) for file in sorted(glob.glob("*.{}".format('txt'))): allAnnotationFiles.append(file) for currentName in allAnnotationFiles: tf_example = create_tf_example(currentName, FLAGS.anno_path, FLAGS.image_path) writer.write(tf_example.SerializeToString()) writer.close()if name == 'main': tf.app.run()
does it work for xml file aswell
Hi @paviddavid, Could you try the workaround mentioned on this link. Thank you!
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you.
Closing as stale. Please reopen if you'd like to work on this further.