csv文件内容如下:
在这里插入图片描述
编写脚本generate_tfrecord.py,用于生成TFrecord格式文件,代码内容如下:

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

  # Create test data:
  python generate_tfrecord.py --csv_input=data/test_labels.csv  --output_path=data/test.record --image_dir=images
"""
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.DEFINE_string('image_dir', '', 'Path to images')
FLAGS = flags.FLAGS

# 确保更换为自己的定义的标签  #################
def class_text_to_int(row_label):
    if row_label == 'a':
        return 1
    elif row_label == 'b':
        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(FLAGS.image_dir)
    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 % 10 == 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()

注意: generate_tfrecord.py文件放在tensorflowAPI 的/models/research/目录下,使用命令,运行程序:

# 生成train.record:
python generate_tfrecord.py --csv_input=data/train_labels.csv  --output_path=data/train.record --image_dir=images
# 生成test.record:
python generate_tfrecord.py --csv_input=data/test_labels.csv  --output_path=data/test.record --image_dir=images

生成的TFrecord格式文件如下:
在这里插入图片描述

GitHub 加速计划 / la / labelImg
22.31 K
6.24 K
下载
🎉 超级实用!LabelImg,图像标注神器,现在加入Label Studio社区,享受多模态数据标注新体验!🚀 简单易用,支持XML、YOLO和CreateML格式,适用于ImageNet等项目。不再单独维护,立即尝试Label Studio,安装一键到位,更灵活,功能更强大!👇 安装即刻开始:pip3 install labelImg,或访问<https://github.com/heartexlabs/label-studio> 获取源码构建。一起探索数据标注的新边界!👨‍💻👩‍💻【此简介由AI生成】
最近提交(Master分支:2 个月前 )
b33f965b Adds information about Label Studio community to welcome LabelImg users 2 年前
2d5537ba 2 年前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐