json转voc(python)

json2voc.py

import os
import numpy as np
import codecs
import json
from glob import glob
import cv2
import shutil
from sklearn.model_selection import train_test_split
from tqdm import tqdm
import pandas as pd

defect_name2label = {
    '破洞': 1, '水渍': 2, '油渍': 2, '污渍': 2, '三丝': 3, '结头': 4, '花板跳': 5, '百脚': 6, '毛粒': 7,
    '粗经': 8, '松经': 9, '断经': 10, '吊经': 11, '粗维': 12, '纬缩': 13, '浆斑': 14, '整经结': 15, '星跳': 16, '跳花': 16,
    '断氨纶': 17, '稀密档': 18, '浪纹档': 18, '色差档': 18, '磨痕': 19, '轧痕': 19, '修痕': 19, '烧毛痕': 19, '死皱': 20, '云织': 20,
    '双纬': 20, '双经': 20, '跳纱': 20, '筘路': 20, '纬纱不良': 20,
}

# 1.标签路径
image_path1 = "F:/guangdong/guangdong1_round1_train1_20190818/defect_Images/"  # 原始labelme标注数据路径
image_path2 = "F:/guangdong/guangdong1_round1_train2_20190828/defect_Images/"  # 原始labelme标注数据路径
saved_path = "VOC2007/"  # 保存路径

# 2.创建要求文件夹
if not os.path.exists(saved_path + "Annotations"):
    os.makedirs(saved_path + "Annotations")
if not os.path.exists(saved_path + "JPEGImages/"):
    os.makedirs(saved_path + "JPEGImages/")
if not os.path.exists(saved_path + "ImageSets/Main/"):
    os.makedirs(saved_path + "ImageSets/Main/")

json_file1 = "F:/guangdong/guangdong1_round1_train1_20190818/Annotations/anno_train.json" #比赛json格式路径
json_file2 = "F:/guangdong/guangdong1_round1_train2_20190828/Annotations/anno_train.json"
files = [1]
# 4.读取标注信息并写入 xml
for json_file in [json_file1, json_file2]:
    anno_result = pd.read_json(open(json_file, "r"))
    file_name_list = list(set(anno_result['name']))

    for file_name in tqdm(file_name_list):

        with codecs.open(saved_path + "Annotations/" + file_name.split('.')[0] + ".xml", "w", "utf-8") as xml:
            height, width, channels = 1000, 2446, 3

            xml.write('<annotation>\n')
            xml.write('\t<folder>' + 'VOC2007' + '</folder>\n')
            xml.write('\t<filename>' + file_name + '</filename>\n')
            xml.write('\t<source>\n')
            xml.write('\t\t<database>The UAV autolanding</database>\n')
            xml.write('\t\t<annotation>UAV AutoLanding</annotation>\n')
            xml.write('\t\t<image>flickr</image>\n')
            xml.write('\t\t<flickrid>NULL</flickrid>\n')
            xml.write('\t</source>\n')
            xml.write('\t<owner>\n')
            xml.write('\t\t<flickrid>NULL</flickrid>\n')
            xml.write('\t\t<name>GuangDongDec</name>\n')
            xml.write('\t</owner>\n')
            xml.write('\t<size>\n')
            xml.write('\t\t<width>' + str(width) + '</width>\n')
            xml.write('\t\t<height>' + str(height) + '</height>\n')
            xml.write('\t\t<depth>' + str(channels) + '</depth>\n')
            xml.write('\t</size>\n')
            xml.write('\t\t<segmented>0</segmented>\n')

            bbox = anno_result[anno_result['name'] == file_name]
            for box, defect_name in zip(bbox['bbox'], bbox['defect_name']):
                points = np.array(box)
                xmin = points[0]
                xmax = points[2]
                ymin = points[1]
                ymax = points[3]
                label = defect_name2label[defect_name]
                if xmax <= xmin:
                    pass
                elif ymax <= ymin:
                    pass
                else:
                    xml.write('\t<object>\n')
                    xml.write('\t\t<name>' + str(label) + '</name>\n')
                    xml.write('\t\t<pose>Unspecified</pose>\n')
                    xml.write('\t\t<truncated>1</truncated>\n')
                    xml.write('\t\t<difficult>0</difficult>\n')
                    xml.write('\t\t<bndbox>\n')
                    xml.write('\t\t\t<xmin>' + str(xmin) + '</xmin>\n')
                    xml.write('\t\t\t<ymin>' + str(ymin) + '</ymin>\n')
                    xml.write('\t\t\t<xmax>' + str(xmax) + '</xmax>\n')
                    xml.write('\t\t\t<ymax>' + str(ymax) + '</ymax>\n')
                    xml.write('\t\t</bndbox>\n')
                    xml.write('\t</object>\n')
                # print(multi['name'],xmin,ymin,xmax,ymax,label)
            xml.write('</annotation>')

# 5.复制图片到 VOC2007/JPEGImages/下

for image_path in [image_path1, image_path2]:
    image_files = glob(image_path + "*.jpg")
    print("copy image files to VOC007/JPEGImages/")
    for image in tqdm(image_files):
        shutil.copy(image, saved_path + "JPEGImages/")

# #6.split files for txt
txtsavepath = saved_path + "ImageSets/Main/"
ftrainval = open(txtsavepath + '/trainval.txt', 'w')
ftest = open(txtsavepath + '/test.txt', 'w')
ftrain = open(txtsavepath + '/train.txt', 'w')
fval = open(txtsavepath + '/val.txt', 'w')
total_files = glob("VOC2007/Annotations/*.xml")
total_files = [i.split("/")[-1].split(".xml")[0] for i in total_files]
# test_filepath = ""
for file in total_files:
    ftrainval.write(file + "\n")
# test
# for file in os.listdir(test_filepath):
#     ftest.write(file.split(".jpg")[0] + "\n")
# split
train_files, val_files = train_test_split(total_files, test_size=0.15, random_state=42)
# train
for file in train_files:
    ftrain.write(file + "\n")
# val
for file in val_files:
    fval.write(file + "\n")

ftrainval.close()
ftrain.close()
fval.close()
ftest.close()

### 回答1: COCO格式的JSON换为VOC格式的XML需要经过以下几个步骤: 第一步,读取COCO格式的JSON文件,解析其中的对象标注数据。一般来说,COCO格式的JSON中每个对象标注都包含类别、边界框位置、标注区域等信息。 第二步,根据解析得到的标注信息,生成VOC格式的XML文件。在生成XML文件时,需要按照VOC格式的要求,设置好文件头和对象标注信息。每个对象标注都需要有其类别、边界框位置、标注区域等信息。 第三步,将生成的VOC格式的XML文件保存到指定路径下。 其中,关于换的实现细节需要注意以下几点: 首先,在解析COCO格式的JSON文件时,需要根据JSON结构中不同的字段和嵌套关系,逐层解析并提取出标注信息。其中,需要注意一些数据格式的换,如COCO格式中的标注区域信息通常是多边形或RLE格式,需要根据VOC格式要求化为矩形。 其次,在生成VOC格式的XML文件时,需要注意文件头的设置,并遵守XML文档的一些规范。例如,每个XML文件都需要有一个根节点,对象标注的信息需要封装在“object”标签中,且标签中的文本内容需要进行编码和义。 最后,在保存XML文件时,需要确保文件目录存在及权限设置正确。此外,还可以为XML文件设置其它元信息,如创建时间、文件格式等。 综上所述,将COCO格式的JSON文件换为VOC格式的XML需要按照一定的规则解析和生成文件,实现上需要注意一些细节。 ### 回答2: 要将COCO格式的JSON文件换为VOC格式的XML文件,需要进行以下步骤: 1.准备好COCO格式的JSON文件和VOC格式的模板XML文件。 2.读取COCO格式的JSON文件,可以使用Python中的json模块来实现。 3.遍历JSON文件中的所有目标,提取出相应的信息,例如目标的类别、位置等。 4.将提取出的信息填写到VOC格式的XML模板中,并保存成XML文件。 5.可以使用Python中的xml.etree.ElementTree模块来实现XML文件的创建和编辑。 6.将换后的XML文件导入到目标检测框架中进行训练和测试。 需要注意的是,COCO格式和VOC格式有很大的差异,因此在换过程中需要特别小心。同时,也需要根据具体的数据集和目标检测框架的要求进行相应的修改和调整。 ### 回答3: COCO (Common Objects in Context)格式是一种常用的目标检测数据集格式,而VOC (Visual Object Classes)格式是另一种经常用于目标检测任务的格式。在实际应用中,有时需要将COCO格式的数据换为VOC格式,以便在某些特定场景中使用。 要将COCO格式JSON换为VOC格式XML,需要进行以下几个步骤: 1. 解析COCO格式JSON数据,获得图片路径、图片大小以及目标检测框的坐标、类别等信息。 2. 根据得到的类别信息,确定VOC格式XML中用于表示目标类别的ID号。 3. 将解析得到的图片大小以及目标框坐标换为VOC格式需要的左上角坐标、右下角坐标等信息。 4. 根据得到的信息,生成VOC格式XML文件。其中,每个目标检测框对应一个对象节点,包含对象的类别、位置等信息。 需要注意的是,COCO格式和VOC格式的差异比较大,对于某些特定的键值对,需要进行相应的换或忽略。此外,在进行数据换时,应注意保留足够的信息,以便后续任务能够顺利进行。 总的来说,将COCO格式JSON换为VOC格式XML需要较为复杂的代码实现,对于没有相关经验的人来说难度较大,建议寻求专业人士的帮助。
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值