tensorflow object detection 准备自己的数据集

前一篇博文已经安装好了tensorflow的object detection 模块。本博文主要记录如何准备自己的数据集。

参考博文:

TensorFlow Object Detection API教程——制作自己的数据集

深度学习入门篇--手把手教你用 TensorFlow 训练模型

https://github.com/datitran/raccoon_dataset


一、标记数据

1、使用精灵标注助手进行标记数据。


二、将数据集转换为TFRecord文件格式。本部分参考博文

1、将标记的xml文件分为train test validation三部分。

其中src_xml目录下存放着标签xml文件,有多少张标记的图片,就有多少个xml文件。运行完以后,annotations文件夹下就放好了分类的xml,annotations有三个目录,分别是train,test,validation。代码如下  :

import os
import random
import time
import shutil

xmlfilepath = r'src_xml'
saveBasePath = r"./annotations"

trainval_percent = 0.9
train_percent = 0.85
total_xml = os.listdir(xmlfilepath)
num = len(total_xml)
list = range(num)
tv = int(num * trainval_percent)
tr = int(tv * train_percent)
trainval = random.sample(list, tv)
train = random.sample(trainval, tr)

print("train and val size", tv)
print("train size", tr)
# print(total_xml[1])
start = time.time()

# print(trainval)
# print(train)

test_num = 0
val_num = 0
train_num = 0
# for directory in ['train','test',"val"]:
#         xml_path = os.path.join(os.getcwd(), 'annotations/{}'.format(directory))
#         if(not os.path.exists(xml_path)):
#             os.mkdir(xml_path)
#         # shutil.copyfile(filePath, newfile)
#         print(xml_path)
for i in list:
    name = total_xml[i]
    # print(i)
    if i in trainval:  # train and val set
        # ftrainval.write(name)
        if i in train:
            # ftrain.write(name)
            # print("train")
            # print(name)
            # print("train: "+name+" "+str(train_num))
            directory = "train"
            train_num += 1
            xml_path = os.path.join(os.getcwd(), 'annotations/{}'.format(directory))
            if (not os.path.exists(xml_path)):
                os.makedirs(xml_path)
            filePath = os.path.join(xmlfilepath, name)
            newfile = os.path.join(saveBasePath, os.path.join(directory, name))
            shutil.copyfile(filePath, newfile)

        else:
            # fval.write(name)
            # print("val")
            # print("val: "+name+" "+str(val_num))
            directory = "validation"
            xml_path = os.path.join(os.getcwd(), 'annotations/{}'.format(directory))
            if (not os.path.exists(xml_path)):
                os.makedirs(xml_path)
            val_num += 1
            filePath = os.path.join(xmlfilepath, name)
            newfile = os.path.join(saveBasePath, os.path.join(directory, name))
            shutil.copyfile(filePath, newfile)
            # print(name)
    else:  # test set
        # ftest.write(name)
        # print("test")
        # print("test: "+name+" "+str(test_num))
        directory = "test"
        xml_path = os.path.join(os.getcwd(), 'annotations/{}'.format(directory))
        if (not os.path.exists(xml_path)):
            os.makedirs(xml_path)
        test_num += 1
        filePath = os.path.join(xmlfilepath, name)
        newfile = os.path.join(saveBasePath, os.path.join(directory, name))
        shutil.copyfile(filePath, newfile)
        # print(name)

# End time
end = time.time()
seconds = end - start
print("train total : " + str(train_num))
print("validation total : " + str(val_num))
print("test total : " + str(test_num))
total_num = train_num + val_num + test_num
print("total number : " + str(total_num))
print("Time taken : {0} seconds".format(seconds))

2、把xml转换成csv文件。

运行完成后,在annotations文件夹所在目录下,会生成一个data文件夹,里面存放着生成的csv文件,代码如下: 

import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET


def xml_to_csv(path):
    xml_list = []
    for xml_file in glob.glob(path + '/*.xml'):
        tree = ET.parse(xml_file)
        root = tree.getroot()
        # print(root)
        print(root.find('filename').text)
        for member in root.findall('object'):
            value = (root.find('filename').text,
                     int(root.find('size')[1].text),  # width
                     int(root.find('size')[2].text),  # height
                     member[0].text,
                     int(member[4][0].text),
                     int(float(member[4][1].text)),
                     int(member[4][2].text),
                     int(member[4][3].text)
                     )
            xml_list.append(value)
    column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']
    xml_df = pd.DataFrame(xml_list, columns=column_name)
    return xml_df


def main():
    save_dir = os.path.join(os.getcwd(), 'data')
    if (not os.path.exists(save_dir)):
        os.mkdir(save_dir)
    for directory in ['train', 'test', 'validation']:
        xml_path = os.path.join(os.getcwd(), 'annotations/{}'.format(directory))
        xml_df = xml_to_csv(xml_path)
        xml_df.to_csv('data/whsyxt_{}_labels.csv'.format(directory), index=None)
        print('Successfully converted xml to csv.')


main()

3、转换成tfrecords文件

运行一下代码,将csv文件,转换成tfrecords文件。

"""
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
"""
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.app.flags
# flags.DEFINE_string('csv_input', 'data/whsyxt_train_labels.csv', 'Path to the CSV input')
# flags.DEFINE_string('output_path', 'data/whsyxt_train.tfrecord', 'Path to output TFRecord')

# flags.DEFINE_string('csv_input', 'data/whsyxt_test_labels.csv', 'Path to the CSV input')
# flags.DEFINE_string('output_path', 'data/whsyxt_test.tfrecord', 'Path to output TFRecord')

flags.DEFINE_string('csv_input', 'data/whsyxt_validation_labels.csv', 'Path to the CSV input')
flags.DEFINE_string('output_path', 'data/whsyxt_validation.tfrecord', 'Path to output TFRecord')
FLAGS = flags.FLAGS


# TO-DO replace this with label map
def class_text_to_int(row_label):
    if row_label == 'person':
        return 1
    elif row_label == 'car':
        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.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.python_io.TFRecordWriter(FLAGS.output_path)
    path = os.path.join(os.getcwd(), 'images')
    examples = pd.read_csv(FLAGS.csv_input)
    grouped = split(examples, 'filename')
    num = 0
    for group in grouped:
        num += 1
        tf_example = create_tf_example(group, path)
        writer.write(tf_example.SerializeToString())
        if (num % 100 == 0):  # 每完成100个转换,打印一次
            print(num)

    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()

猜你喜欢

转载自blog.csdn.net/hust_bochu_xuchao/article/details/79677533