将voc格式数据集转为coco格式数据集,以及问题解答。

voc转coco步骤

1、整理需要的voc文件,包括下述内容

其中annotations中存放的是xml注解,images存放的是图片
其中annotations中存放的是xml注解,images存放的是图片

存放xml文件
存放xml文件

存放图片文件
存放图片文件

2、将voc转化为coco的代码,一步到位

import xml.etree.ElementTree as ET
import os
import json
# 初始化了一个名为 coco 的字典,用于构建一个COCO(Common Objects in Context)数据结构
coco = dict()
#用于存储图像信息的列表。
coco['images'] = []
# 被设置为 'instances',表明这是一个实例分割任务的数据集。
coco['type'] = 'instances'
#  用于存储标注信息的列表。
coco['annotations'] = []
# 用于存储类别信息的列表。
coco['categories'] = []

category_set = dict({'car':1})#是一个字典,包含一个类别'car',对应值为1
image_set = set()#集合,用于存储图像文件名

category_item_id = 0#整数变量,用于标识类别项ID
image_id = 20180000000#用于表示图像ID
annotation_id = 0#用于标识注释ID


# 用于向COCO数据集中添加类别项
def addCatItem(name):#name类别项名称
    global category_item_id#全局变量,表示类别项ID
    category_item = dict()
    category_item['supercategory'] = 'none'
    category_item_id += 1
    category_item['id'] = category_item_id
    category_item['name'] = name
    coco['categories'].append(category_item)
    category_set[name] = category_item_id
    return category_item_id

# 用于向某个数据结构(可能是COCO数据集)中添加图像项的函数。这段代码的作用是根据传入的文件名和大小信息,创建一个包含图像信息的字典,并将其添加到COCO数据结构中。
def addImgItem(file_name, size):
    global image_id
    if file_name is None:
        raise Exception('Could not find filename tag in xml file.')
    if size['width'] is None:
        raise Exception('Could not find width tag in xml file.')
    if size['height'] is None:
        raise Exception('Could not find height tag in xml file.')
    image_id += 1
    image_item = dict()
    image_item['id'] = image_id
    image_item['file_name'] = file_name
    image_item['width'] = size['width']
    image_item['height'] = size['height']
    coco['images'].append(image_item)
    image_set.add(file_name)
    return image_id

# 这段代码定义了一个函数 addAnnoItem,用于向COCO数据结构中添加标注项。函数的参数包括目标对象的名称 (object_name)、图像的ID (image_id)、类别的ID (category_id) 以及边界框的坐标信息 (bbox)。
def addAnnoItem(object_name, image_id, category_id, bbox):
    global annotation_id
    annotation_item = dict()
    annotation_item['segmentation'] = []
    seg = []
    # bbox[] is x,y,w,h
    # left_top
    seg.append(bbox[0])
    seg.append(bbox[1])
    # left_bottom
    seg.append(bbox[0])
    seg.append(bbox[1] + bbox[3])
    # right_bottom
    seg.append(bbox[0] + bbox[2])
    seg.append(bbox[1] + bbox[3])
    # right_top
    seg.append(bbox[0] + bbox[2])
    seg.append(bbox[1])

    annotation_item['segmentation'].append(seg)

    annotation_item['area'] = bbox[2] * bbox[3]
    annotation_item['iscrowd'] = 0
    annotation_item['ignore'] = 0
    annotation_item['image_id'] = image_id
    annotation_item['bbox'] = bbox
    annotation_item['category_id'] = category_id
    annotation_id += 1
    annotation_item['id'] = annotation_id
    coco['annotations'].append(annotation_item)


# 这段代码定义了一个名为 _read_image_ids 的函数,用于从一个文件中读取图像的ID。具体来说,函数的作用是:
# 打开指定的图像集文件 image_sets_file。
# 逐行读取文件内容,将每行去除末尾的换行符后的结果添加到列表 ids 中。
# 返回包含所有图像ID的列表 ids。
def _read_image_ids(image_sets_file):
    ids = []
    with open(image_sets_file) as f:
        for line in f:
            ids.append(line.rstrip())
    return ids



def parseXmlFiles(xml_path, json_save_path):#xml_path=ann_path=annotations
    for f in os.listdir(xml_path):#筛选出annotations以.xml结尾的文件
        if not f.endswith('.xml'):
            continue

        bndbox = dict()
        size = dict()
        current_image_id = None
        current_category_id = None
        file_name = None
        size['width'] = None
        size['height'] = None
        size['depth'] = None

        xml_file = os.path.join(xml_path, f)
        print(xml_file)#打印出需要处理的文件名

        tree = ET.parse(xml_file)
        root = tree.getroot()
        if root.tag != 'annotation':
            raise Exception('pascal voc xml root element should be annotation, rather than {}'.format(root.tag))

        # elem is <folder>, <filename>, <size>, <object>
        #
        for elem in root:
            current_parent = elem.tag
            current_sub = None
            object_name = None

            if elem.tag == 'folder':
                continue

            if elem.tag == 'filename':
                # file_name = elem.text
                file_name = f[:-3] + 'jpg'
                if file_name in category_set:
                    raise Exception('file_name duplicated')

            # add img item only after parse <size> tag
            elif current_image_id is None and file_name is not None and size['width'] is not None:
            # elif current_image_id is None and file_name is  None and size['width'] is  None:
                if file_name not in image_set:
                    current_image_id = addImgItem(file_name, size)
                    print('add image with {} and {}'.format(file_name, size))
                else:
                    raise Exception('duplicated image: {}'.format(file_name))
                    # subelem is <width>, <height>, <depth>, <name>, <bndbox>
            for subelem in elem:
                bndbox['xmin'] = None
                bndbox['xmax'] = None
                bndbox['ymin'] = None
                bndbox['ymax'] = None

                current_sub = subelem.tag
                if current_parent == 'object' and subelem.tag == 'name':
                    object_name = subelem.text
                    if object_name not in category_set:
                        current_category_id = addCatItem(object_name)
                    else:
                        current_category_id = category_set[object_name]

                elif current_parent == 'size':
                    if size[subelem.tag] is not None:
                        raise Exception('xml structure broken at size tag.')
                    size[subelem.tag] = int(subelem.text)

                # option is <xmin>, <ymin>, <xmax>, <ymax>, when subelem is <bndbox>
                for option in subelem:
                    if current_sub == 'bndbox':
                        if bndbox[option.tag] is not None:
                            raise Exception('xml structure corrupted at bndbox tag.')
                        # bndbox[option.tag] = int(option.text)
                        bndbox[option.tag] = float(option.text)

                # only after parse the <object> tag
                if bndbox['xmin'] is not None:
                    if object_name is None:
                        raise Exception('xml structure broken at bndbox tag,object_name is none')
                    if current_image_id is None:
                        raise Exception('xml structure broken at bndbox tag,current_image_id is None')
                    if current_category_id is None:
                        raise Exception('xml structure broken at bndbox tag,current_category_id is None')
                    bbox = []
                    # x
                    bbox.append(bndbox['xmin'])
                    # y
                    bbox.append(bndbox['ymin'])
                    # w
                    bbox.append(bndbox['xmax'] - bndbox['xmin'])
                    # h
                    bbox.append(bndbox['ymax'] - bndbox['ymin'])
                    print('add annotation with {},{},{},{}'.format(object_name, current_image_id, current_category_id,
                                                                   bbox))
                    addAnnoItem(object_name, current_image_id, current_category_id, bbox)
    json.dump(coco, open(json_save_path, 'w'))






if __name__ == '__main__':
   dataset_dir = "./detr/train_daysunny/images"#存放voc数据集图片的路径
    ann_path = "./detr/train_daysunny/annotations"#存放voc数据集xml文件的路径
    json_save_path = "./COCO/annotations/coco.json"#转化之后coco.json文件的路径。PS:coco.json文件需要自己手动提前创建成功。
    parseXmlFiles(ann_path, json_save_path)
    print("生成完成。")





3、根据xml文件里的格式不同,适当调整上述代码

1、第一种情况

在这里插入图片描述
如果xml文件里的格式是这种的话,那就可以直接使用上述代码,不需要调整。
因为如图所示:
在这里插入图片描述
代码本身要找的xml文件中的元素就是folder,filename,size,object与上述xml文件中的格式是对应的,所以可以直接转化。(PS:如果碰到其他小问题自己解决)

2、第二种情况

在这里插入图片描述
xml文件中的格式与第一种情况稍微有些不同,比如说没有folder,filename改为name等等。这个时候就需要调整我们的代码。
调整之后的代码如下:

import xml.etree.ElementTree as ET
import os
import json
# 初始化了一个名为 coco 的字典,用于构建一个COCO(Common Objects in Context)数据结构
coco = dict()
#用于存储图像信息的列表。
coco['images'] = []
# 被设置为 'instances',表明这是一个实例分割任务的数据集。
coco['type'] = 'instances'
#  用于存储标注信息的列表。
coco['annotations'] = []
# 用于存储类别信息的列表。
coco['categories'] = []

category_set = dict({'car':1})#是一个字典,包含一个类别'car',对应值为1
image_set = set()#集合,用于存储图像文件名

category_item_id = 0#整数变量,用于标识类别项ID
image_id = 20180000000#用于表示图像ID
annotation_id = 0#用于标识注释ID


# 用于向COCO数据集中添加类别项
def addCatItem(name):#name类别项名称
    global category_item_id#全局变量,表示类别项ID
    category_item = dict()
    category_item['supercategory'] = 'none'
    category_item_id += 1
    category_item['id'] = category_item_id
    category_item['name'] = name
    coco['categories'].append(category_item)
    category_set[name] = category_item_id
    return category_item_id

# 用于向某个数据结构(可能是COCO数据集)中添加图像项的函数。这段代码的作用是根据传入的文件名和大小信息,创建一个包含图像信息的字典,并将其添加到COCO数据结构中。
def addImgItem(file_name):
    global image_id
    if file_name is None:
        raise Exception('Could not find filename tag in xml file.')

    image_id += 1
    image_item = dict()
    image_item['id'] = image_id
    image_item['file_name'] = file_name

    coco['images'].append(image_item)
    image_set.add(file_name)
    return image_id

# 这段代码定义了一个函数 addAnnoItem,用于向COCO数据结构中添加标注项。函数的参数包括目标对象的名称 (object_name)、图像的ID (image_id)、类别的ID (category_id) 以及边界框的坐标信息 (bbox)。
def addAnnoItem(object_name, image_id, category_id, bbox):
    global annotation_id
    annotation_item = dict()
    annotation_item['segmentation'] = []
    seg = []
    # bbox[] is x,y,w,h
    # left_top
    seg.append(bbox[0])
    seg.append(bbox[1])
    # left_bottom
    seg.append(bbox[0])
    seg.append(bbox[1] + bbox[3])
    # right_bottom
    seg.append(bbox[0] + bbox[2])
    seg.append(bbox[1] + bbox[3])
    # right_top
    seg.append(bbox[0] + bbox[2])
    seg.append(bbox[1])

    annotation_item['segmentation'].append(seg)

    annotation_item['area'] = bbox[2] * bbox[3]
    annotation_item['iscrowd'] = 0
    annotation_item['ignore'] = 0
    annotation_item['image_id'] = image_id
    annotation_item['bbox'] = bbox
    annotation_item['category_id'] = category_id
    annotation_id += 1
    annotation_item['id'] = annotation_id
    coco['annotations'].append(annotation_item)


# 这段代码定义了一个名为 _read_image_ids 的函数,用于从一个文件中读取图像的ID。具体来说,函数的作用是:
# 打开指定的图像集文件 image_sets_file。
# 逐行读取文件内容,将每行去除末尾的换行符后的结果添加到列表 ids 中。
# 返回包含所有图像ID的列表 ids。
def _read_image_ids(image_sets_file):
    ids = []
    with open(image_sets_file) as f:
        for line in f:
            ids.append(line.rstrip())
    return ids



def parseXmlFiles(xml_path, json_save_path):#xml_path=ann_path=annotations
    for f in os.listdir(xml_path):#筛选出annotations以.xml结尾的文件
        if not f.endswith('.xml'):
            continue

        bndbox = dict()
        size = dict()
        current_image_id = None
        current_category_id = None
        file_name = None
        size['width'] = None
        size['height'] = None
        size['depth'] = None

        xml_file = os.path.join(xml_path, f)
        print(xml_file)#打印出需要处理的文件名

        tree = ET.parse(xml_file)
        root = tree.getroot()
        if root.tag != 'annotation':
            raise Exception('pascal voc xml root element should be annotation, rather than {}'.format(root.tag))
        print(xml_file)
        # elem is <folder>, <filename>, <size>, <object>
        #
        for elem in root:
            current_parent = elem.tag
            current_sub = None
            object_name = None

            # if elem.tag == 'folder':
            #     continue

            if elem.tag == 'name':
                # file_name = elem.text
                file_name = f[:-3] + 'jpg'
                print("111")
                if file_name in category_set:
                    raise Exception('file_name duplicated')

            # add img item only after parse <size> tag
            elif current_image_id is None and file_name is not None:
            # elif current_image_id is None and file_name is  None and size['width'] is  None:
                if file_name not in image_set:
                    current_image_id = addImgItem(file_name)
                    print('add image with {} '.format(file_name))
                else:
                    raise Exception('duplicated image: {}'.format(file_name))
                    # subelem is <width>, <height>, <depth>, <name>, <bndbox>
            for subelem in elem:
                bndbox['xmin'] = None
                bndbox['xmax'] = None
                bndbox['ymin'] = None
                bndbox['ymax'] = None

                current_sub = subelem.tag
                if current_parent == 'object' and subelem.tag == 'name':
                    object_name = subelem.text
                    if object_name not in category_set:
                        current_category_id = addCatItem(object_name)
                    else:
                        current_category_id = category_set[object_name]

                elif current_parent == 'size':
                    if size[subelem.tag] is not None:
                        raise Exception('xml structure broken at size tag.')
                    size[subelem.tag] = int(subelem.text)

                # option is <xmin>, <ymin>, <xmax>, <ymax>, when subelem is <bndbox>
                for option in subelem:
                    if current_sub == 'bndbox':
                        if bndbox[option.tag] is not None:
                            raise Exception('xml structure corrupted at bndbox tag.')
                        # bndbox[option.tag] = int(option.text)
                        bndbox[option.tag] = float(option.text)

                # only after parse the <object> tag
                if bndbox['xmin'] is not None:
                    if object_name is None:
                        raise Exception('xml structure broken at bndbox tag,object_name is none')
                    if current_image_id is None:
                        raise Exception('xml structure broken at bndbox tag,current_image_id is None')
                    if current_category_id is None:
                        raise Exception('xml structure broken at bndbox tag,current_category_id is None')
                    bbox = []
                    # x
                    bbox.append(bndbox['xmin'])
                    # y
                    bbox.append(bndbox['ymin'])
                    # w
                    bbox.append(bndbox['xmax'] - bndbox['xmin'])
                    # h
                    bbox.append(bndbox['ymax'] - bndbox['ymin'])
                    print('add annotation with {},{},{},{}'.format(object_name, current_image_id, current_category_id,
                                                                   bbox))
                    addAnnoItem(object_name, current_image_id, current_category_id, bbox)
    json.dump(coco, open(json_save_path, 'w'))






if __name__ == '__main__':
    dataset_dir = "./detr/train_daysunny/images"#存放voc数据集图片的路径
    ann_path = "./detr/train_daysunny/annotations"#存放voc数据集xml文件的路径
    json_save_path = "./COCO/annotations/coco.json"#转化之后coco.json文件的路径。PS:coco.json文件需要自己手动提前创建成功。
    parseXmlFiles(ann_path, json_save_path)
    print("生成完成。")





3、其他情况

剩下的情况,具体问题具体分析了。

4、批量修改文件名的代码

# 批量修改文件名,默认操作为将图片按1,2,3,,,顺序重命名

import os

path_in = "./detr/train_daysunny/images"  # 待批量重命名的文件夹
class_name = ".jpg"  # 重命名后的文件名后缀

file_in = os.listdir(path_in)  # 返回文件夹包含的所有文件名
num_file_in = len(file_in)  # 获取文件数目
print(file_in, num_file_in)  # 输出修改前的文件名

for i in range(0, num_file_in):
    t = str(i + 1)
    new_name = os.rename(path_in + "/" + file_in[i], path_in + "/" + t + class_name)  # 重命名文件名

file_out = os.listdir(path_in)
print(file_out)  # 输出修改后的结果
四级标题
五级标题
六级标题
  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值