labelme转换voc和coco


前言

将labelme标注好的标签转为标准voc和coco格式。


一、介绍voc和coco

1.voc

└─VOC2007
    ├─JPEGImages
    │  ├─1.jpg
    │  ├─2.jpg
    │  └─3.jpg
    ├─Annotations
    │  ├─1.xml
    │  ├─2.xml
    │  └─3.xm
    ├─ImageSets
    │  ├─Layout
    │  │  ├─train.txt
    │  │  ├─trainva.txt
    │  │  ├─test.txt
    │  │  └─val.txt
    │  ├─Main
    │  │  ├─*_train.txt
    │  │  ├─*_trainva.txt
    │  │  ├─*_test.txt
    │  │  └─*_val.txt
    │  ├─Action
    │  │  ├─*_train.txt
    │  │  ├─*_trainva.txt
    │  │  ├─*_test.txt
    │  │  └─*_val.txt
    │  └─Segmentation
    │     ├─train.txt
    │     ├─trainva.txt
    │     ├─test.txt
    │     └─val.txt
    ├─SegmentationClass
└─SegmentationObject

如果要制作xml标注的自定义VOC格式的数据集,只需要构建三个文件夹,分别是:
JPEGImages用于存放所有原始图像;
Annotations存放所有的和原始图像名称对应的xml标注文件;ImageSets/Main中存放train.txt、val.txt和test.txt等用来进行数据集划分,这些txt文件可以手动划分好,也可以使用代码随机划分,需要注意的是txt文件内容一行为一个不加拓展名的文件名即可。

构建VOC格式的数据集还是很简单的,因为LabelImg等工具生成的xml标注就是VOC格式需要的。

2.coco

─coco2017
    ├─annotations
    │  ├─instances_train2017.json
    │  ├─instances_val2017.json
    │  └─*.json
    ├─train2017
    │  ├─1.jpg
    │  ├─2.jpg
    │  └─3.jpg
    ├─val2017
    │  ├─4.jpg
    │  ├─5.jpg
    │  └─6.jpg
    ├─test2017
    │  ├─7.jpg
    │  ├─8.jpg
    │  └─9.xml
    └─unlabeled2017

和VOC不同的是,COCO整个训练集的标注都在一个文件内。我们构造的时候只要生成子集文件夹和标注文件夹即可,标注文件夹每个json对应一个子集的标注。

二、labelme转换

1.labelme2voc.py

代码如下:

import cv2
import json
import os
import os.path as osp
import shutil
import chardet

def get_encoding(path):
    f = open(path, 'rb')
    data = f.read()
    file_encoding = chardet.detect(data).get('encoding')
    f.close()
    return file_encoding

def is_pic(img_name):
    valid_suffix = ['JPEG', 'jpeg', 'JPG', 'jpg', 'BMP', 'bmp', 'PNG', 'png']
    suffix = img_name.split('.')[-1]
    if suffix not in valid_suffix:
        return False
    return True


class X2VOC(object):
    def __init__(self):
        pass

    def convert(self, image_dir, json_dir, dataset_save_dir):
        """转换。
        Args:
            image_dir (str): 图像文件存放的路径。
            json_dir (str): 与每张图像对应的json文件的存放路径。
            dataset_save_dir (str): 转换后数据集存放路径。
        """
        assert osp.exists(image_dir), "The image folder does not exist!"
        assert osp.exists(json_dir), "The json folder does not exist!"
        if not osp.exists(dataset_save_dir):
            os.makedirs(dataset_save_dir)
        # Convert the image files.
        new_image_dir = osp.join(dataset_save_dir, "JPEGImages")
        if osp.exists(new_image_dir):
            raise Exception(
                "The directory {} is already exist, please remove the directory first".
                format(new_image_dir))
        os.makedirs(new_image_dir)
        for img_name in os.listdir(image_dir):
            if is_pic(img_name):
                shutil.copyfile(
                    osp.join(image_dir, img_name),
                    osp.join(new_image_dir, img_name))
        # Convert the json files.
        xml_dir = osp.join(dataset_save_dir, "Annotations")
        if osp.exists(xml_dir):
            raise Exception(
                "The directory {} is already exist, please remove the directory first".
                format(xml_dir))
        os.makedirs(xml_dir)
        self.json2xml(new_image_dir, json_dir, xml_dir)


class LabelMe2VOC(X2VOC):
    """将使用LabelMe标注的数据集转换为VOC数据集。
    """
    def json2xml(self, image_dir, json_dir, xml_dir):
        import xml.dom.minidom as minidom
        i = 0
        for img_name in os.listdir(image_dir):
            img_name_part = osp.splitext(img_name)[0]
            json_file = osp.join(json_dir, img_name_part + ".json")
            i += 1
            if not osp.exists(json_file):
                os.remove(osp.join(image_dir, img_name))
                continue
            xml_doc = minidom.Document()
            root = xml_doc.createElement("annotation")
            xml_doc.appendChild(root)
            node_folder = xml_doc.createElement("folder")
            node_folder.appendChild(xml_doc.createTextNode("JPEGImages"))
            root.appendChild(node_folder)
            node_filename = xml_doc.createElement("filename")
            node_filename.appendChild(xml_doc.createTextNode(img_name))
            root.appendChild(node_filename)
            with open(json_file, mode="r", \
                      encoding=get_encoding(json_file)) as j:
                json_info = json.load(j)
                if 'imageHeight' in json_info and 'imageWidth' in json_info:
                    h = json_info["imageHeight"]
                    w = json_info["imageWidth"]
                else:
                    img_file = osp.join(image_dir, img_name)
                    im_data = cv2.imread(img_file)
                    h, w, c = im_data.shape
                node_size = xml_doc.createElement("size")
                node_width = xml_doc.createElement("width")
                node_width.appendChild(xml_doc.createTextNode(str(w)))
                node_size.appendChild(node_width)
                node_height = xml_doc.createElement("height")
                node_height.appendChild(xml_doc.createTextNode(str(h)))
                node_size.appendChild(node_height)
                node_depth = xml_doc.createElement("depth")
                node_depth.appendChild(xml_doc.createTextNode(str(3)))
                node_size.appendChild(node_depth)
                root.appendChild(node_size)
                for shape in json_info["shapes"]:
                    if 'shape_type' in shape:
                        if shape["shape_type"] != "rectangle":
                            continue
                        (xmin, ymin), (xmax, ymax) = shape["points"]
                        xmin, xmax = sorted([xmin, xmax])
                        ymin, ymax = sorted([ymin, ymax])
                    else:
                        points = shape["points"]
                        points_num = len(points)
                        x = [points[i][0] for i in range(points_num)]
                        y = [points[i][1] for i in range(points_num)]
                        xmin = min(x)
                        xmax = max(x)
                        ymin = min(y)
                        ymax = max(y)
                    label = shape["label"]
                    node_obj = xml_doc.createElement("object")
                    node_name = xml_doc.createElement("name")
                    node_name.appendChild(xml_doc.createTextNode(label))
                    node_obj.appendChild(node_name)
                    node_diff = xml_doc.createElement("difficult")
                    node_diff.appendChild(xml_doc.createTextNode(str(0)))
                    node_obj.appendChild(node_diff)
                    node_box = xml_doc.createElement("bndbox")
                    node_xmin = xml_doc.createElement("xmin")
                    node_xmin.appendChild(xml_doc.createTextNode(str(xmin)))
                    node_box.appendChild(node_xmin)
                    node_ymin = xml_doc.createElement("ymin")
                    node_ymin.appendChild(xml_doc.createTextNode(str(ymin)))
                    node_box.appendChild(node_ymin)
                    node_xmax = xml_doc.createElement("xmax")
                    node_xmax.appendChild(xml_doc.createTextNode(str(xmax)))
                    node_box.appendChild(node_xmax)
                    node_ymax = xml_doc.createElement("ymax")
                    node_ymax.appendChild(xml_doc.createTextNode(str(ymax)))
                    node_box.appendChild(node_ymax)
                    node_obj.appendChild(node_box)
                    root.appendChild(node_obj)
            with open(osp.join(xml_dir, img_name_part + ".xml"), 'w') as fxml:
                xml_doc.writexml(
                    fxml,
                    indent='\t',
                    addindent='\t',
                    newl='\n',
                    encoding="utf-8")


def convert(pics,anns,save_dir):
    """
    将使用labelme标注的数据转换为VOC格式
    请将labelme标注的文件中,所有img文件保存到pics文件夹中,所有xml文件保存到anns文件夹中,结构如下:
            --labelmedata
            ---pics
            ----img0.jpg
            ----img1.jpg
            ----......
            ---anns
            ----img0.mxl
            ----img1.xml
            ----......
    :param pics: img文件所在文件夹的路径
    :param anns: xml文件所在文件夹的路径
    :param save_dir: 输出VOC格式数据的保存路径
    :return:
    """
    labelme2voc = LabelMe2VOC().convert
    labelme2voc(pics, anns, save_dir)

if __name__=="__main__":
    convert(pics=r"D:\WorkSpace\zh(v3-clearML)\test_dataset\Downloads\img",
            anns=r"D:\WorkSpace\zh(v3-clearML)\test_dataset\Downloads\anns",
            save_dir=r"D:\WorkSpace\zh(v3-clearML)\test_dataset\Downloads\VOC")

2.labelme2coco.py

代码如下:

"""
    将使用labelme标注的数据转换为COCO格式
    labelme标注的文件中,所有json文件在js文件夹中,结构如下:

            --js文件夹
            -----coco文件夹
            -----labelme2coco.py
            -----0.json
            -----1.json
            -----...
"""

import json
import os

from numpy.ma import sort


def labelme2coco(labelme_json=[], save_json_path='./coco.json'):
    coco_json = {
    
    }
    coco_json['images'] = []
    coco_json['annotations'] = []
    coco_json['categories'] = []

    class_name_to_id = {
    
    }

    for i, label_file in enumerate(labelme_json):
        with open(label_file, 'r') as f:
            label_data = json.load(f)

        image_data = {
    
    }
        image_data['id'] = i
        image_data['file_name'] = os.path.basename(label_data['imagePath'])
        image_data['height'] = label_data['imageHeight']
        image_data['width'] = label_data['imageWidth']
        coco_json['images'].append(image_data)

        for shape in label_data['shapes']:
            class_name = shape['label']
            if class_name not in class_name_to_id:
                class_id = len(class_name_to_id)
                class_name_to_id[class_name] = class_id
                category_data = {
    
    }
                category_data['id'] = class_id
                category_data['name'] = class_name
                coco_json['categories'].append(category_data)
            else:
                class_id = class_name_to_id[class_name]

            points = shape['points']
            x1, y1 = points[0]
            x2, y2 = points[1]
            annotation_data = {
    
    }
            annotation_data['id'] = len(coco_json['annotations'])
            annotation_data['image_id'] = i
            annotation_data['category_id'] = class_id
            annotation_data['bbox'] = [x1, y1, x2 - x1, y2 - y1]
            annotation_data['area'] = (x2 - x1) * (y2 - y1)
            coco_json['annotations'].append(annotation_data)

    with open(save_json_path, 'w') as f:
        json.dump(coco_json, f)


def get_file(dir_path):
    file_list = []
    for root, dirs, files in os.walk(dir_path):
        for file in files:
            #if file.endswith("xlsx") or file.endswith("csv"):
            if file.endswith("json"):
                file_list.append(os.path.join(root, file))

    return sort(file_list)

#labelme_json = ['0.json', '1.json']
#js_file_path= r'/js'
js_fileList = get_file(os.getcwd())
#print(js_fileList)
save_json_path = './coco/coco.json'
labelme2coco(js_fileList, save_json_path)

总结

简单记录下如何将labelme标注得到的标签转化为VOC或者COCO标准格式。


引用

VOC数据格式介绍: https://blog.csdn.net/qingfengxiaosong/article/details/130257862
COCO数据格式介绍: https://blog.csdn.net/qingfengxiaosong/article/details/130258025
labelme2voc: https://github.com/thgpddl/CodeHub/blob/main/DeepLearn/LabelMe2VOC.py
labelme2coco: https://github.com/thgpddl/CodeHub/blob/main/DeepLearn/LabelMe2COCO.py
https://pythonjishu.com/gmdxgpwmmxuhanb/

猜你喜欢

转载自blog.csdn.net/qq_45734610/article/details/131813724