xml格式的数据集转coco格式的代码

原文链接在这里:https://blog.csdn.net/w113691/article/details/80817186?utm_source=blogxgwz2
对部分信息进行了改动,希望能有帮助

# -*- coding:utf-8 -*-
# !/usr/bin/env python

import argparse
import json
import matplotlib.pyplot as plt
import skimage.io as io
import cv2
#from labelme import utils
import numpy as np
import glob
import PIL.Image
import os, sys

class PascalVOC2coco(object):
    def __init__(self, xml = [], 
    save_json_path='/disk/data/*'):

        '''
        :param xml: 所有Pascal VOC的xml文件路径组成的列表
        :param save_json_path: json保存位置
        '''
        self.xml = xml
        self.save_json_path = save_json_path
        self.images = []
        self.categories = []
        self.cls = ('write your dataset classes')
# * means the number of your dataset category
        self.id = dict(zip(self.cls, range(1, *)))
        self.annotations = []
        self.label = []
        self.annID = 1
        self.height = 0
        self.width = 0
        self.ob = []
        self.save_json()

    def data_transfer(self):
        for num, json_file in enumerate(self.xml):
            # 进度输出
            sys.stdout.write('\r>> Converting image %d/%d' % (
                num + 1, len(self.xml)))
            sys.stdout.flush()
            self.json_file = json_file
            self.num = num
            path = os.path.dirname(self.json_file)
            # print(path)
            path = os.path.dirname(path)
            obj_path = glob.glob(os.path.join(path, 'SegmentationObject', '*.png'))
            # print(obj_path)
            with open(json_file, 'r') as fp:
                # print(fp)
                flag = 0
                for p in fp:
                    # print(p)
                    # if 'folder' in p:
                    #     folder =p.split('>')[1].split('<')[0]
                    f_name = 1
                    if 'filename' in p:
                        self.filen_ame = p.split('>')[1].split('<')[0]
                        # print(self.filen_ame)
                        f_name = 0

                        self.path = os.path.join(path, 'SegmentationObject', self.filen_ame.split('.')[0] + '.png')
                        # if self.path not in obj_path:
                        #    break

                    if 'width' in p:
                        self.width = int(p.split('>')[1].split('<')[0])
                        # print(self.width)
                    if 'height' in p:
                        self.height = int(p.split('>')[1].split('<')[0])

                        self.images.append(self.image())
                        # print(self.image())

                    if flag == 1:
                        for i in range(1, 21):
                            if i ==  self.id[self.ob[0]]:
                                self.supercategory = self.ob[0]

                                if self.supercategory not in self.label:
                                    self.categories.append(self.categorie())
                                    self.label.append(self.supercategory)

                       
                        # 边界框
                        x1 = int(self.ob[1])
                        y1 = int(self.ob[2])
                        x2 = int(self.ob[3])
                        y2 = int(self.ob[4])
                        self.rectangle = [x1, y1, x2, y2]
                        self.bbox = [x1, y1, x2 - x1, y2 - y1]  # COCO 对应格式[x,y,w,h]
                        self.area = (x2-x1) *(y2-y1)
                        self.annotations.append(self.annotation())
                        self.annID += 1
                        self.ob = []
                        flag = 0
                    elif f_name == 1:
                        if 'name' in p:
                            self.ob.append(p.split('>')[1].split('<')[0])

                        if 'xmin' in p:
                            self.ob.append(p.split('>')[1].split('<')[0])

                        if 'ymin' in p:
                            self.ob.append(p.split('>')[1].split('<')[0])

                        if 'xmax' in p:
                            self.ob.append(p.split('>')[1].split('<')[0])

                        if 'ymax' in p:
                            self.ob.append(p.split('>')[1].split('<')[0])
                            flag = 1


        sys.stdout.write('\n')
        sys.stdout.flush()

    def image(self):
        image = {}
        image['height'] = self.height
        image['width'] = self.width
        image['id'] = self.num + 1
        image['file_name'] = self.filen_ame
        return image

    def categorie(self):
        categorie = {}
        categorie['supercategory'] = self.supercategory
        categorie['id'] = self.id[self.supercategory] 
        categorie['name'] = self.supercategory
        return categorie

    def annotation(self):
        annotation = {}
        annotation['area']= self.area
        annotation['segmentation'] = [list(map(float, self.getsegmentation()))]
        annotation['iscrowd'] = 0
        annotation['image_id'] = self.num + 1
        annotation['bbox'] = self.bbox
        annotation['category_id'] = self.getcatid(self.supercategory)
        annotation['id'] = self.annID
        return annotation

    def getcatid(self, label):
        for categorie in self.categories:
            if label == categorie['name']:
                return categorie['id']
        return -1

    def getsegmentation(self):

        try:
            mask_1 = cv2.imread(self.path, 0)
            mask = np.zeros_like(mask_1, np.uint8)
            rectangle = self.rectangle
            mask[rectangle[1]:rectangle[3], rectangle[0]:rectangle[2]] = mask_1[rectangle[1]:rectangle[3],
                                                                         rectangle[0]:rectangle[2]]

            # 计算矩形中点像素值
            mean_x = (rectangle[0] + rectangle[2]) // 2
            mean_y = (rectangle[1] + rectangle[3]) // 2

            end = min((mask.shape[1], int(rectangle[2]) + 1))
            start = max((0, int(rectangle[0]) - 1))

            flag = True
            for i in range(mean_x, end):
                x_ = i
                y_ = mean_y
                pixels = mask_1[y_, x_]
                if pixels != 0 and pixels != 220:  # 0 对应背景 220对应边界线
                    mask = (mask == pixels).astype(np.uint8)
                    flag = False
                    break
            if flag:
                for i in range(mean_x, start, -1):
                    x_ = i
                    y_ = mean_y
                    pixels = mask_1[y_, x_]
                    if pixels != 0 and pixels != 220:
                        mask = (mask == pixels).astype(np.uint8)
                        break
            self.mask = mask

            return self.mask2polygons()

        except:
            return [0]

    def mask2polygons(self):
        contours = cv2.findContours(self.mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)  # 找到轮廓线
        bbox = []
        for cont in contours[1]:
            [bbox.append(i) for i in list(cont.flatten())]
            # map(bbox.append,list(cont.flatten()))
        return bbox  # list(contours[1][0].flatten())

    # '''
    def getbbox(self, points):
        # img = np.zeros([self.height,self.width],np.uint8)
        # cv2.polylines(img, [np.asarray(points)], True, 1, lineType=cv2.LINE_AA)  # 画边界线
        # cv2.fillPoly(img, [np.asarray(points)], 1)  # 画多边形 内部像素值为1
        polygons = points
        mask = self.polygons_to_mask([self.height, self.width], polygons)
        return self.mask2box(mask)

    def mask2box(self, mask):
        '''从mask反算出其边框
        mask:[h,w]  0、1组成的图片
        1对应对象,只需计算1对应的行列号(左上角行列号,右下角行列号,就可以算出其边框)
        '''
        # np.where(mask==1)
        index = np.argwhere(mask == 1)
        rows = index[:, 0]
        clos = index[:, 1]
        # 解析左上角行列号
        left_top_r = np.min(rows)  # y
        left_top_c = np.min(clos)  # x

        # 解析右下角行列号
        right_bottom_r = np.max(rows)
        right_bottom_c = np.max(clos)
        return [left_top_c, left_top_r, right_bottom_c - left_top_c,
                right_bottom_r - left_top_r]  # [x1,y1,w,h] 对应COCO的bbox格式

    def polygons_to_mask(self, img_shape, polygons):
        mask = np.zeros(img_shape, dtype=np.uint8)
        mask = PIL.Image.fromarray(mask)
        xy = list(map(tuple, polygons))
        PIL.ImageDraw.Draw(mask).polygon(xy=xy, outline=1, fill=1)
        mask = np.array(mask, dtype=bool)
        return mask

    # '''
    def data2coco(self):
        data_coco = {}
        data_coco['images'] = self.images
        data_coco['categories'] = self.categories
        data_coco['annotations'] = self.annotations
        return data_coco

    def save_json(self):
        self.data_transfer()
        self.data_coco = self.data2coco()
        # 保存json文件
        json.dump(self.data_coco, open(self.save_json_path, 'w'), indent=4)  # indent=4 更加美观显示

# * means the list file(example:00001,0002……)
file_root = os.path.join('/disk/*.txt')
assert os.path.exists(file_root), 'Path does not exist: {}'.format(file_root)
with open(file_root, 'r') as f:
    lines = f.readlines()
list_file = [line.strip() for line in lines]
xml = []
for i in range(0, len(lines), 1):
    xml_root = '/disk/{}.xml'.format(list_file[i])

    xml.append(xml_root)
#* means the json file that you want to save
PascalVOC2coco(xml, '/disk/*.json')

### 回答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、付费专栏及课程。

余额充值