tensorflow object detection api 目标检测(数据集生成)

简介:

在做车牌识别时,使用官方提供的模块制作tfrecord数据集时,踩了很多坑,于是网上找了一个代码,自己拿来解剖才搞定的。下面是我解剖的过程,希望对新手有帮助。

这篇博客主要讲CSV文件转成tfrecord文件, xml文件转换成csv文件没有遇到bug,所以就 不讨论了。

csv文件数据:

模块讲解:

模块一,文本标注:

'''
把文本标注的类转换成数值,存储在tfrecord的label中
输入: class -> 标签名称
输出: label -> 分类的结果 
'''
def class_text_to_int(row_label):
    if row_label =='plate':   #  plate 对应csv文件中class的标签,如果有多个标签一一列举即可。
        return 1
    else:
        return None

pd读入csv文件:

使用pd读入数据格式后,打印出来的结果,对应模块 输入的df

模块二 csv文件分割:

调用格式: 

'''
输入值: 一个csv文件数据
返回值: 元组列表
''' 

def split(df, group):
    data = namedtuple('data', ['filename', 'object'])
    gb = df.groupby(group)
    result = [data(filename, gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)]

    print(result[0])   # -->元组列表
    print(type(result[0]))  # --><class '__main__.data'>
    return result

元组列表解释:

result[0] = data(filename='云F58999.jpg', 
object=      filename  width  height  class  xmin  ymin  xmax  ymax         pose  truncated  difficult
0  云F58999.jpg    300       3  plate   159   167   234   192  Unspecified          0          0)

result[0].filename= '云F58999.jpg'

result[0].filename.object =  

第一行:     filename  width  height  class  xmin  ymin  xmax  ymax         pose  truncated  difficult
第二行:0  云F58999.jpg    300       3  plate   159   167   234   192  Unspecified          0          0)

上一行的第一个0对应表格的标号。可见,object把csv文件的每一列都取出来了,并分别给上表头而已。

注意: object输出的是两行

大坑:

下面两行代码是图片的文件路径+文件名,如果找不到文件,报一堆的错。就因为这个错误,我把生成数据集的每一行代码弄明白了,才找到的。   如果你也遇到跟我一样的问题,建议专门把这行代码拿出来调试。

with tf.gfile.GFile(os.path.join(path, '{}'.format(group.filename)), 'rb') as fid:
        encoded_jpg = fid.read()

创建tfrecord样列子:

    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), # label name
        'image/object/class/label': dataset_util.int64_list_feature(classes), # label num
    }))

这是tfrecord创建样列的标准格式(字典格式),如果还想增加内容,就往后面添加key-value对就行了。

讲解几个不好理解的数据:

encoded -> 这里装的是图片的二进制数据 utf-8格式

format  -.> 图片格式,支持jpg,png格式

text       -> 这个对应csv文件中的class,字符串格式

label    -> 这个就是模块一打的标签

 

tf.app.flags:

这个 模块的功能类似于argv, 不同的是,他是以key-value的格式输入的, -

格式: ---xxx aaa  -->表示,建为xxx, 值为aaa

这里主要 用在文件名的输入上。

使用方式:

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

以上是定义csv_input为输入的建,默认值为'data/whsyxt_validation_labels.csv',表示如果终端不带key-value时,就使用这个值。

第三个输入表示描述,方便理解。

命令终端输入格式: 没有截取前面的 python段,自己添加吧

直接上源码吧:

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_validation_labels.csv', 'Path to the CSV input')
flags.DEFINE_string('output_path', 'data/whsyxt_train.tfrecord', 'Path to output TFRecord')
FLAGS = flags.FLAGS
image_path = r'E:\tensorflow\objection\database\车牌识别\images'

# TO-DO replace this with label map
'''
把文本标注的类转换成数值,存储在tfrecord的label中
输入: class -> 标签名称
输出: label -> 分类的结果 
'''
def class_text_to_int(row_label):
    if row_label =='plate':
        return 1
    else:
        return None
 
'''
输入值: 一个csv文件数据
返回值: 元组列表
result[0] = data(filename='云F58999.jpg', 
object=      filename  width  height  class  xmin  ymin  xmax  ymax         pose  truncated  difficult
0  云F58999.jpg    300       3  plate   159   167   234   192  Unspecified          0          0)
类型:type(result[0]) --》<class '__main__.data'>
''' 
def split(df, group):
    data = namedtuple('data', ['filename', 'object'])
    gb = df.groupby(group)
    result = [data(filename, gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)]
    print(result[0])
    print(type(result[0]))
    return result
 
 
def create_tf_example(group, path):
    with tf.gfile.GFile(os.path.join(image_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('utf-8')
    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('utf-8')) 
#        classes_text.append(row['class'])
        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), # label name
        'image/object/class/label': dataset_util.int64_list_feature(classes), # label num
    }))
    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)
#    print(examples)
    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()
 

只 需要修改三个位置即可用于你的csv文件 转换成tfrecoord,就是三个路径,下面这行的路径对应着该就行了,

分别是 csv文件路径,文件输出路径,图片路径

flags.DEFINE_string('csv_input', 'data/whsyxt_validation_labels.csv', 'Path to the CSV input')
flags.DEFINE_string('output_path', 'data/whsyxt_train.tfrecord', 'Path to output TFRecord')
FLAGS = flags.FLAGS
image_path = r'E:\tensorflow\objection\database\车牌识别\images'

提示:这是生成 图片数据的中间环节, 这里的代码对于新手来说不容易懂,就写了一个注释。其他的环节 自己百度吧。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值