coco(json)、yolo(txt)、voc(xml)标注格式的相互转换

一般都是用labeleme进行标注 标注格式都是json

然后根据不同的格式进行数据标注转换:

1.逐个json转xml:

当我们在使用数据集训练计算机视觉模型时,常常会遇到有的数据集只给了单个的json annotation文件,而模型所需要的annotation是基于每个图片的xml annotation文件

# translate coco_json to xml
import os
import time
import json
import pandas as pd
from tqdm import tqdm
from pycocotools.coco import COCO
 
 
def trans_id(category_id):
    names = []
    namesid = []
    for i in range(0, len(cats)):
        names.append(cats[i]['name'])
        namesid.append(cats[i]['id'])
        # print('id:{1}\t {0}'.format(names[i], namesid[i]))
    index = namesid.index(category_id)
    return index
 
root = r''  # 你下载的 COCO 数据集所在目录
dataType = '2019'
anno = r'' # annotation json 文件所在位置
xml_dir = r'' # 导出的xml文件所在的位置
 
coco = COCO(anno)  # 读文件
cats = coco.loadCats(coco.getCatIds())  # 这里loadCats就是coco提供的接口,获取类别
 
# Create anno dir
dttm = time.strftime("%Y%m%d%H%M%S", time.localtime())
# if os.path.exists(xml_dir):
#     os.rename(xml_dir, xml_dir + dttm)
# os.mkdir(xml_dir)
 
with open(anno, 'r') as load_f:
    f = json.load(load_f)
 
imgs = f['images']  # json文件的img_id和图片对应关系 imgs列表表示多少张图
 
cat = f['categories']
df_cate = pd.DataFrame(f['categories'])  # json中的类别
df_cate_sort = df_cate.sort_values(["id"], ascending=True)  # 按照类别id排序
categories = list(df_cate_sort['name'])  # 获取所有类别名称
print('categories = ', categories)
df_anno = pd.DataFrame(f['annotations'])  # json中的annotation
 
for i in tqdm(range(len(imgs))):  # 大循环是images所有图片
    xml_content = []
    file_name = imgs[i]['file_name']  # 通过img_id找到图片的信息
    height = imgs[i]['height']
    img_id = imgs[i]['id']
    width = imgs[i]['width']
 
    # xml文件添加属性
    xml_content.append("<annotation>")
    xml_content.append("	<folder>VOC2007</folder>")
    xml_content.append("	<filename>" + file_name.split('/')[1].split('.')[0] + '.jpg' + "</filename>")
    xml_content.append("	<size>")
    xml_content.append("		<width>" + str(width) + "</width>")
    xml_content.append("		<height>" + str(height) + "</height>")
    xml_content.append("	</size>")
    xml_content.append("	<segmented>0</segmented>")
 
    # 通过img_id找到annotations
    annos = df_anno[df_anno["image_id"].isin([img_id])]  # (2,8)表示一张图有两个框
 
    for index, row in annos.iterrows():  # 一张图的所有annotation信息
        bbox = row["bbox"]
        category_id = row["category_id"]
        # cate_name = categories[trans_id(category_id)]
        cate_name = cat[category_id-1]['name']
 
        # add new object
        xml_content.append("<object>")
        xml_content.append("<name>" + cate_name + "</name>")
        xml_content.append("<pose>Unspecified</pose>")
        xml_content.append("<truncated>0</truncated>")
        xml_content.append("<difficult>0</difficult>")
        xml_content.append("<bndbox>")
        xml_content.append("<xmin>" + str(int(bbox[0])) + "</xmin>")
        xml_content.append("<ymin>" + str(int(bbox[1])) + "</ymin>")
        xml_content.append("<xmax>" + str(int(bbox[0] + bbox[2])) + "</xmax>")
        xml_content.append("<ymax>" + str(int(bbox[1] + bbox[3])) + "</ymax>")
        xml_content.append("</bndbox>")
        xml_content.append("</object>")
    xml_content.append("</annotation>")
 
    x = xml_content
    xml_content = [x[i] for i in range(0, len(x)) if x[i] != "\n"]
    ### list存入文件
    xml_path = os.path.join(xml_dir, file_name.replace('.jpg', '.xml'))
    with open(xml_path, 'w+', encoding="utf8") as f:
        f.write('\n'.join(xml_content))
    xml_content[:] = []

2.逐个xml转txt:

# xml_to_yolo_txt.py
# 此代码和VOC_KITTI文件夹同目录
import os
import xml.etree.ElementTree as ET
# 这里的类名为我们xml里面的类名,顺序a按照Readme文件,或者也可以不考虑顺序
# 其中thermal类别比rgb类别多了dog和deer,生成txt注意区分  # 我统一都写成thermal的类别了
class_names = ['person','bike','car','motor', 'bus', 'train','truck','light','hydrant', 'sign','dog','deer',
               'skateboard','stroller', 'scooter', 'other vehicle']
# class_names = ['person','bike','car','motor', 'bus', 'train','truck','light','hydrant', 'sign',
#                'skateboard','stroller','scooter','other vehicle' ]
# xml文件路径
path = 'G:/红外数据集-FLIR2/FLIR2_yolo_xml/images_rgb_val/data/'
# 转换一个xml文件为txt
def single_xml_to_txt(xml_file):
    tree = ET.parse(os.path.join(path, xml_file))
    root = tree.getroot()
    # 保存的txt文件路径
    txt_file = os.path.join('G:/红外数据集-FLIR2/FLIR2_yolo_txt/images_rgb_val/data/', xml_file.split('.')[0]+'.txt')
    with open(txt_file, 'w') as txt_file:
        for member in root.findall('object'):
            #filename = root.find('filename').text
            picture_width = int(root.find('size')[0].text)
            picture_height = int(root.find('size')[1].text)
            class_name = member[0].text
            # 类名对应的index
            class_num = class_names.index(class_name)

            box_x_min = int(member[4][0].text) # 左上角横坐标
            box_y_min = int(member[4][1].text) # 左上角纵坐标
            box_x_max = int(member[4][2].text) # 右下角横坐标
            box_y_max = int(member[4][3].text) # 右下角纵坐标
            # 转成相对位置和宽高
            x_center = float(box_x_min + box_x_max) / (2 * picture_width)
            y_center = float(box_y_min + box_y_max) / (2 * picture_height)
            width = float(box_x_max - box_x_min) /  picture_width
            height = float(box_y_max - box_y_min) /  picture_height
            # print(class_num, x_center, y_center, width, height)
            txt_file.write(str(class_num) + ' ' + str(x_center) + ' ' + str(y_center) + ' ' + str(width) + ' ' + str(height) + '\n')
# 转换文件夹下的所有xml文件为txt
def dir_xml_to_txt(path):
    files = os.listdir(path)
    for xml_file in files:
        single_xml_to_txt(xml_file)
dir_xml_to_txt(path)

3. 逐个json转txt  (生成coco数据集/yolo数据集格式)

(1.) 这里首先对xx.jpg,xx.json统一成coco格式,生成instances_train2017/instances_val2017

定义lables.txt是:(注意_background_是-1)

_background_
person
car
bicycle
UAV
motorcycle
xxx

目录结构: 

|-- images
|     |---  1.jpg
|     |---  1.json
|     |---  2.jpg
|     |---  2.json
|     |---  .......
|-- labelmejson2coco.py
|-- labels.txt

(2)labelmejson2coco.py文件,整理成coco数据集格式


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TracyGC

创作不易,需要花花~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值