目标检测:TF2.0版本,将voc格式(.xml)转成 tfrecord 格式

第一,先标注图像,(精灵标注,略)

附一个将标注坐标在原图上画出的小脚本

# -*- coding: utf-8 -*-
#目标图像检测 之  将标注的图像坐标提取,并在原图上画出来
import xml.etree.ElementTree as ET  
import os
import cv2
 
xml_file='D:/AAAAA/4T/outputs/4T_110.xml'
tree=ET.parse(xml_file)
root=tree.getroot()
imgfile='D:/AAAAA/4T/4T_110.jpg'
im = cv2.imread(imgfile)
for i in range(1):
    for object in root.findall('object'):
        object_name=object.find('name').text
        Xmin=int(object.find('bndbox').find('xmin').text)
        Ymin=int(object.find('bndbox').find('ymin').text)
        Xmax=int(object.find('bndbox').find('xmax').text)
        Ymax=int(object.find('bndbox').find('ymax').text)
        color = (4, 250, 7)
        cv2.rectangle(im,(Xmin,Ymin),(Xmax,Ymax),color,2)
        print((Xmin,Ymin),(Xmax,Ymax))
        font = cv2.FONT_HERSHEY_SIMPLEX  
        cv2.putText(im, object_name, (Xmin,Ymin - 7), font, 0.5, (6, 230, 230), 2)
        cv2.imshow('01',im)
cv2.waitKey(0)
#cv2.imwrite('02.jpg', im)

第二,将xml格式转换成csv格式


#tf2.0 目标检测之 VOC xml格式转 CSV
import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET
 
os.chdir('D:\\AAAAA\\test') 
path = 'D:\\AAAAA\\test'  #xml地址
 
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'):
            print(type(member))
            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']
    xml_df = pd.DataFrame(xml_list, columns=column_name)
    return xml_df
 
 
def main():
    image_path = path
    xml_df = xml_to_csv(image_path)
    xml_df.to_csv('test.csv', index=None)
    print('Successfully converted xml to csv.')
 
 
main()

第三、将csv转成TFrecord格式(test和train分别执行)

#tf2.0目标检测之csv 2 Tfrecord
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import

import os
import io
import pandas as pd
from PIL import Image
from collections import namedtuple

import tensorflow as tf



# CSV文件的位置
csv_input = 'D:/AAAAA/xml_csv_tfrecord/train.csv'
# TFRecords的输出位置及文件名
output_path = 'D:/AAAAA/xml_csv_tfrecord/train.record'
# 图像数据的位置
image_dir = 'D:/AAAAA/trainImage/'


def class_text_to_int(row_label):
    if row_label == 'T':
        return 0
    elif row_label == '1':
        return 1
    elif row_label == '2':
        return 2
    elif row_label == '3':
        return 3
    elif row_label == '4':
        return 4
    elif row_label == '5':
        return 5
    elif row_label == '6':
        return 6
    elif row_label == '7':
        return 7
    elif row_label == '8':
        return 8
    elif row_label == '9':
        return 9
    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.io.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': tf.train.Feature(int64_list=tf.train.Int64List(value=[height])),
        'image/width': tf.train.Feature(int64_list=tf.train.Int64List(value=[width])),
        'image/filename':tf.train.Feature(bytes_list=tf.train.BytesList(value=[filename])),
        'image/source_id': tf.train.Feature(bytes_list=tf.train.BytesList(value=[filename])),
        'image/encoded': tf.train.Feature(bytes_list=tf.train.BytesList(value=[encoded_jpg])),
        'image/format': tf.train.Feature(bytes_list=tf.train.BytesList(value=[image_format])),
        'image/object/bbox/xmin': tf.train.Feature(float_list=tf.train.FloatList(value=xmins)),
        'image/object/bbox/xmax':  tf.train.Feature(float_list=tf.train.FloatList(value=xmaxs)),
        'image/object/bbox/ymin': tf.train.Feature(float_list=tf.train.FloatList(value=ymins)),
        'image/object/bbox/ymax':tf.train.Feature(float_list=tf.train.FloatList(value=ymaxs)),
        'image/object/class/text': tf.train.Feature(bytes_list=tf.train.BytesList(value=classes_text)),
        'image/object/class/label': tf.train.Feature(int64_list=tf.train.Int64List(value=classes)),
    }))
    return tf_example

def main():
    writer = tf.io.TFRecordWriter(output_path)
    path = os.path.join(os.getcwd(), image_dir)
    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()
    
if __name__ == '__main__':
    main()

到这里会得到test.tfrecord和train.tfrecord两个tensorflow格式的文件。接下就可以进行读取和训练了。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值