欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

打标签制作自己的数据集并在TensorFlow框架上训练

程序员文章站 2022-04-08 09:09:56
...

标签工具labelImg

用labelimg对自己的数据做好标注,只有一类预测桃子图像。
注释文件保存为xml格式,满足PASCAL VOC风格,如下图1把图片和标签放在一个文件夹内(data)打标签制作自己的数据集并在TensorFlow框架上训练

转换数据格式,可以在tensorflow框架下读取

需将标记完的数据集xml的文件转换为TFRecord格式的文件
1、先转换为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()
        for member in root.findall('object'):
            value = (root.find('filename').text,
                     int(root.find('size')[0].text),
                     int(root.find('size')[1].text),
                     member[0].text,
                     int(member[4][0].text),
                     int(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']

    # 将所有数据分为样本集和验证集,一般按照3:1的比例
    train_list = xml_list[0: int(len(xml_list) * 0.67)]
    eval_list = xml_list[int(len(xml_list) * 0.67) + 1: ]

    # 保存为CSV格式
    train_df = pd.DataFrame(train_list, columns=column_name)
    eval_df = pd.DataFrame(eval_list, columns=column_name)
    train_df.to_csv('D:/programs/models-master/research/object_detection/data/train_peaches.csv', index=None)
    eval_df.to_csv('D:/programs/models-master/research/object_detection/data/eval_peaches.csv', index=None)

def main():
    path = 'D:/dataset/data'
    xml_to_csv(path)
    print('Successfully converted xml to csv.')
main()

2、再转换为TFRecord格式
转换代码为:

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', '', 'Path to the CSV input')
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
FLAGS = flags.FLAGS

# 将分类名称转成ID号
def class_text_to_int(row_label):
    if row_label == 'peach':
        return 1
    else:
        print('NONE: ' + row_label)
        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):
    print(os.path.join(path, '{}'.format(group.filename)))
    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(csv_input, output_path, imgPath):
    writer = tf.python_io.TFRecordWriter(output_path)
    path = imgPath
    examples = pd.read_csv(csv_input)
    grouped = split(examples, 'filename')
    for group in grouped:
        tf_example = create_tf_example(group, path)
        writer.write(tf_example.SerializeToString())

    writer.close()
    print('Successfully created the TFRecords: {}'.format(output_path))

if __name__ == '__main__':

    imgPath = 'D:/dataset/data'
    
    # 生成train.record文件
    output_path = 'D:/programs/models-master/research/object_detection/data/train_peaches.record'
    csv_input = 'D:/programs/models-master/research/object_detection/data/train_peaches.csv'
    main(csv_input, output_path, imgPath)

    # 生成验证文件 eval.record
    output_path = 'D:/programs/models-master/research/object_detection/data/eval_peaches.record'
    csv_input = 'D:/programs/models-master/research/object_detection/data/eval_peaches.csv'
    main(csv_input, output_path, imgPath)

运行结果

如下图:
打标签制作自己的数据集并在TensorFlow框架上训练

训练自己的数据集

结果如图
打标签制作自己的数据集并在TensorFlow框架上训练
打标签制作自己的数据集并在TensorFlow框架上训练
打标签制作自己的数据集并在TensorFlow框架上训练
参考博客:
https://blog.csdn.net/RobinTomps/article/details/78115628?locationNum=5&fps=1

相关标签: 深度学习