多个xml文件转coco格式、coco转VOC格式(xml)

1、多个xml文件转coco格式

bug已改,已经试过可以用。

只需要修改三个地方:

  1. xml_folder 变量中的路径改为你自己的 xml 文件所在文件夹路径。

  1. class_name 变量中的类别名称改为你自己数据集的类别名称。

  1. json_file 变量中的路径改为你想要保存 COCO 格式注释文件的路径。

然后按住shift+鼠标右键,选择在此处打开powershell,输入 python xxx.py即可转换成功

import logging
import os
import time
import xml.etree.ElementTree as ET
import json

def get_file_list(path, type=".xml"):
    file_names = []
    for maindir, subdir, file_name_list in os.walk(path):
        for filename in file_name_list:
            apath = os.path.join(maindir, filename)
            ext = os.path.splitext(apath)[1]
            if ext == type:
                file_names.append(filename)
    return file_names


def xml_to_coco(ann_path, class_names):
    """
    convert xml annotations to coco_api
    :param ann_path:
    :return:
    """
    class_name_dict = dict(zip(class_names, range(1, len(class_names)+1)))
    print("loading annotations into memory...")
    tic = time.time()
    ann_file_names = get_file_list(ann_path, type=".xml")
    logging.info("Found {} annotation files.".format(len(ann_file_names)))
    image_info = []
    categories = []
    annotations = []
    for idx, supercat in enumerate(class_names):
        categories.append(
            {"supercategory": supercat, "id": idx + 1, "name": supercat}
        )
    ann_id = 1
    for idx, xml_name in enumerate(ann_file_names):
        tree = ET.parse(os.path.join(ann_path, xml_name))
        root = tree.getroot()
        file_name = root.find("filename").text
        width = int(root.find("size").find("width").text)
        height = int(root.find("size").find("height").text)
        info = {
            "file_name": file_name,
            "height": height,
            "width": width,
            "id": idx + 1,
        }
        image_info.append(info)
        for _object in root.findall("object"):
            category = _object.find("name").text
            if category not in class_names:
                print(
                    "WARNING! {} is not in class_names! "
                    "Pass this box annotation.".format(category)
                )
                continue

            cat_id = class_name_dict[category]

            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)
            w = xmax - xmin
            h = ymax - ymin
            if w < 0 or h < 0:
                print(
                    "WARNING! Find error data in file {}! Box w and "
                    "h should > 0. Pass this box annotation.".format(xml_name)
                )
                continue
            coco_box = [max(xmin, 0), max(ymin, 0), min(w, width), min(h, height)]
            ann = {
                "image_id": idx + 1,  # 此处的图片序号,从1开始计算,该bbox所在的图片序号
                "bbox": coco_box,
                "category_id": cat_id,
                "iscrowd": 0,
                "id": ann_id,  # ann_id指的是bbox的序号
                "area": coco_box[2] * coco_box[3],
            }
            annotations.append(ann)  # annotation是一个list,包含了所有bbox的相关信息
            ann_id += 1

    coco_dict = {
        "images": image_info,
        "categories": categories,  # categories,从1开始计算
        "annotations": annotations,
    }

    print("Done (t={:0.2f}s)".format(time.time() - tic))

    return coco_dict


xml_folder = r"D:\documents\Learn\_Code\All_dataset\E\Annotations"
class_name = ['dog',
            ]

coco_dict = xml_to_coco(xml_folder, class_name)

"""
保存为json文件
"""
json_file = r"D:\documents\Learn\DeepLearning_Code\All_dataset\ELinage_All\COCOJson\EL_All.json"
json_fp = open(json_file, 'w')
json_str = json.dumps(coco_dict)
json_fp.write(json_str)
json_fp.close()

2、一个类的coco转VOC格式(xml)

用于一个类的情况

只需要修改6个地方:

  1. CKimg_dir:生成图片保存的路径

  1. CKanno_dir:生成标注文件保存的路径

  1. dataTypes:annotations名称,不带后缀

  1. base_dir:存放转换后的图片和标注的文件夹

  1. origin_image_dir:原始的coco的图像存放位置

  1. origin_anno_dir:原始的coco的标注存放位置

'''
把coco数据集合的所有标注转换到voc格式,不改变图片命名方式,
注意,原来有一些图片是黑白照片,检测出不是 RGB 图像,这样的图像不会被放到新的文件夹中
'''
from pycocotools.coco import COCO
import os, cv2, shutil
from lxml import etree, objectify
from tqdm import tqdm
from PIL import Image

# 1、生成图片保存的路径
CKimg_dir = r'faster_rcnn\balloon\VOC\images'
# 2、生成标注文件保存的路径
CKanno_dir = r'faster_rcnn\balloon\VOC\annotations'


# 若模型保存文件夹不存在,创建模型保存文件夹,若存在,删除重建
def mkr(path):
    if os.path.exists(path):
        shutil.rmtree(path)
        os.mkdir(path)
    else:
        os.mkdir(path)


def save_annotations(filename, objs, filepath):
    annopath = CKanno_dir + "/" + filename[:-3] + "xml"  # 生成的xml文件保存路径
    dst_path = CKimg_dir + "/" + filename
    img_path = filepath
    img = cv2.imread(img_path)
    im = Image.open(img_path)
    # if im.mode != "RGB":
    #     print(filename + " not a RGB image")
    #     im.close()
    #     return
    im.close()
    shutil.copy(img_path, dst_path)  # 把原始图像复制到目标文件夹
    E = objectify.ElementMaker(annotate=False)
    anno_tree = E.annotation(
        E.folder('1'),
        E.filename(filename),
        E.source(
            E.database('CKdemo'),
            E.annotation('VOC'),
            E.image('CK')
        ),
        E.size(
            E.width(img.shape[1]),
            E.height(img.shape[0]),
            E.depth(img.shape[2])
        ),
        E.segmented(0)
    )
    for obj in objs:
        E2 = objectify.ElementMaker(annotate=False)
        anno_tree2 = E2.object(
            E.name(obj[0]),
            E.pose(),
            E.truncated("0"),
            E.difficult(0),
            E.bndbox(
                E.xmin(obj[2]),
                E.ymin(obj[3]),
                E.xmax(obj[4]),
                E.ymax(obj[5])
            )
        )
        anno_tree.append(anno_tree2)
    etree.ElementTree(anno_tree).write(annopath, pretty_print=True)


def showbycv(coco,  img, classes, origin_image_dir, verbose=False):
    filename = img['file_name']
    filepath = os.path.join(origin_image_dir,  filename)
    I = cv2.imread(filepath)
    annIds = coco.getAnnIds(imgIds=img['id'], iscrowd=None)
    anns = coco.loadAnns(annIds)
    objs = []
    for ann in anns:
        name = classes[ann['category_id']]
        if 'bbox' in ann:
            bbox = ann['bbox']
            xmin = (int)(bbox[0])
            ymin = (int)(bbox[1])
            xmax = (int)(bbox[2] + bbox[0])
            ymax = (int)(bbox[3] + bbox[1])
            obj = [name, 1.0, xmin, ymin, xmax, ymax]
            objs.append(obj)
            if verbose:
                cv2.rectangle(I, (xmin, ymin), (xmax, ymax), (255, 0, 0))
                cv2.putText(I, name, (xmin, ymin), 3, 1, (0, 0, 255))
    save_annotations(filename, objs, filepath)
    if verbose:
        cv2.imshow("img", I)
        cv2.waitKey(0)

def catid2name(coco):  # 将名字和id号建立一个字典
    classes = dict()
    for cat in coco.dataset['categories']:
        classes[cat['id']] = cat['name']
        # print(str(cat['id'])+":"+cat['name'])
    return classes


def get_CK5(origin_anno_dir, origin_image_dir, verbose=False):
    dataTypes = ['annotation_coco']       # 3、根据你要转化的是训练集还是验证集(annotations名称)
    for dataType in dataTypes:
        annFile = '{}.json'.format(dataType)
        annpath = os.path.join(origin_anno_dir, annFile)
        coco = COCO(annpath)
        classes = catid2name(coco)
        imgIds = coco.getImgIds()
        # imgIds=imgIds[0:1000]#测试用,抽取10张图片,看下存储效果
        for imgId in tqdm(imgIds):
            img = coco.loadImgs(imgId)[0]
            #showbycv(coco, dataType, img, classes, origin_image_dir, verbose=False)
            showbycv(coco,  img, classes, origin_image_dir, verbose=False)


def main():
    base_dir = r'D:\documents\faster_rcnn\balloon\VOC'  # step1 这里是一个新的文件夹,存放转换后的图片和标注
    image_dir = os.path.join(base_dir, 'images')  # 在上述文件夹中生成images,annotations两个子文件夹
    anno_dir = os.path.join(base_dir, 'annotations')
    mkr(image_dir)
    mkr(anno_dir)
    # 4、
    origin_image_dir = 'train'  # step 2原始的coco的图像存放位置
    # 5、
    origin_anno_dir = 'train'  # step 3 原始的coco的标注存放位置
    print(origin_anno_dir)
    verbose = True  # 是否需要看下标记是否正确的开关标记,若是true,就会把标记展示到图片上
    get_CK5(origin_anno_dir, origin_image_dir, verbose)


if __name__ == "__main__":
    main()

2、多个类的coco转VOC格式(xml)

待补充

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答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需要较为复杂的代码实现,对于没有相关经验的人来说难度较大,建议寻求专业人士的帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值