数据集处理——labelme2voc

本代码用于将labelme标记好的数据转换为voc类型数据集。

#!/usr/bin/env python

from __future__ import print_function

import argparse
import glob
import os
import os.path as osp
import sys
import imgviz
import numpy as np
import labelme

def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument("input_dir", help="input annotated directory")
    parser.add_argument("output_dir", help="output dataset directory")
    parser.add_argument("--labels", help="labels file", required=True)
    parser.add_argument(
        "--noviz", help="no visualization", action="store_true"
    )
    args = parser.parse_args()

    if osp.exists(args.output_dir):
        print("Output directory already exists:", args.output_dir)
        sys.exit(1)
    os.makedirs(args.output_dir)
    os.makedirs(osp.join(args.output_dir, "JPEGImages"))
    os.makedirs(osp.join(args.output_dir, "SegmentationClass"))
    os.makedirs(osp.join(args.output_dir, "SegmentationClassPNG"))
    if not args.noviz:
        os.makedirs(
            osp.join(args.output_dir, "SegmentationClassVisualization")
        )
    os.makedirs(osp.join(args.output_dir, "SegmentationObject"))
    os.makedirs(osp.join(args.output_dir, "SegmentationObjectPNG"))
    if not args.noviz:
        os.makedirs(
            osp.join(args.output_dir, "SegmentationObjectVisualization")
        )
    print("Creating dataset:", args.output_dir)

    class_names = []
    class_name_to_id = {}
    for i, line in enumerate(open(args.labels).readlines()):
        class_id = i - 1  # starts with -1
        class_name = line.strip()
        class_name_to_id[class_name] = class_id
        if class_id == -1:
            assert class_name == "__ignore__"
            continue
        elif class_id == 0:
            assert class_name == "_background_"
        class_names.append(class_name)
    class_names = tuple(class_names)
    print("class_names:", class_names)
    out_class_names_file = osp.join(args.output_dir, "class_names.txt")
    with open(out_class_names_file, "w") as f:
        f.writelines("\n".join(class_names))
    print("Saved class_names:", out_class_names_file)

    for filename in glob.glob(osp.join(args.input_dir, "*.json")):
        print("Generating dataset from:", filename)

        label_file = labelme.LabelFile(filename=filename)

        base = osp.splitext(osp.basename(filename))[0]
        out_img_file = osp.join(args.output_dir, "JPEGImages", base + ".jpg")
        out_cls_file = osp.join(
            args.output_dir, "SegmentationClass", base + ".npy"
        )
        out_clsp_file = osp.join(
            args.output_dir, "SegmentationClassPNG", base + ".png"
        )
        if not args.noviz:
            out_clsv_file = osp.join(
                args.output_dir,
                "SegmentationClassVisualization",
                base + ".jpg",
            )
        out_ins_file = osp.join(
            args.output_dir, "SegmentationObject", base + ".npy"
        )
        out_insp_file = osp.join(
            args.output_dir, "SegmentationObjectPNG", base + ".png"
        )
        if not args.noviz:
            out_insv_file = osp.join(
                args.output_dir,
                "SegmentationObjectVisualization",
                base + ".jpg",
            )

        img = labelme.utils.img_data_to_arr(label_file.imageData)
        imgviz.io.imsave(out_img_file, img)

        cls, ins = labelme.utils.shapes_to_label(
            img_shape=img.shape,
            shapes=label_file.shapes,
            label_name_to_value=class_name_to_id,
        )
        ins[cls == -1] = 0  # ignore it.

        # class label
        labelme.utils.lblsave(out_clsp_file, cls)
        np.save(out_cls_file, cls)
        if not args.noviz:
            clsv = imgviz.label2rgb(
                label=cls,
                img=imgviz.rgb2gray(img),
                label_names=class_names,
                font_size=15,
                loc="rb",
            )
            imgviz.io.imsave(out_clsv_file, clsv)

        # instance label
        labelme.utils.lblsave(out_insp_file, ins)
        np.save(out_ins_file, ins)
        if not args.noviz:
            instance_ids = np.unique(ins)
            instance_names = [str(i) for i in range(max(instance_ids) + 1)]
            insv = imgviz.label2rgb(
                label=ins,
                img=imgviz.rgb2gray(img),
                label_names=instance_names,
                font_size=15,
                loc="rb",
            )
            imgviz.io.imsave(out_insv_file, insv)


if __name__ == "__main__":
    main()

### LabelMe 数据集介绍 LabelMe 是一种用于图像标注的强大工具,允许用户通过图形界面手动绘制多边形来精确地标记物体边界。这种灵活性使得它非常适合处理复杂场景下的对象检测和语义分割任务[^1]。 ### 使用方法概述 对于想要利用 LabelMe 进行数据准备的研究人员来说,通常会经历以下几个方面的工作流程: - **安装软件**:可以通过命令 `pip install labelme` 来快速完成安装操作[^4]。 - **创建项目结构**:建立必要的目录用来存储原始图片以及对应的 JSON 文件形式保存下来的标注信息。 - **启动标注程序**:运行 `labelme` 命令即可打开 GUI 界面,在这里可以选择要编辑的照片并开始标记工作;支持多种形状如矩形、圆形或多边形等以适应不同需求的对象轮廓描绘[^5]。 - **导出为其他框架所需格式**:当完成了初步的标注之后,可以根据目标深度学习库的要求把数据转化为相应的输入格式。例如,可以执行如下Python脚本将标注结果转成Pascal VOC风格或YOLO所需的TXT文件: ```bash python labelme2voc.py input_folder output_folder --labels path_to_labels_file.txt ``` ### 下载链接汇总 网络上存在多个资源分享站点提供了经过 LabelMe 工具加工后的公开可用数据集合供研究者们免费获取使用。以下是几个常见的例子: - 优快云 博客作者 hpg123 分享了一套包含60张船舶影像及其对应标签的小型 YOLO 训练集,可通过 GitCode 平台访问:<https://gitcode.net/a486259/data/-/blob/master/shipdata_yolo.zip> [^2] - 百度网盘也托管了一份由另一位网友整理上传的资料包,内含详细的教程文档及示例代码片段帮助新手入门熟悉整个过程。<https://pan.baidu.com/s/1igKnX9pxi0rcXBiA9HMF3A> (提取码: 1234) ### 格式说明 LabelMe 默认采用 JSON 文件记录每一张图中的所有实例化对象的位置坐标和其他属性描述。一个典型的 JSON 结构看起来像这样: ```json { "version": "4.5.6", "flags": {}, "shapes": [ { "label": "person", "points": [[x1,y1],[x2,y2],...,[xn,yn]], "group_id": null, "shape_type": "polygon", "flags": {} } ], ... } ``` 其中,“label”字段指定了类别名称;而“points”则是一系列二维平面上点组成的列表表示该类别的区域范围。“shape_type”参数决定了这些顶点如何被解析——比如直线连接形成封闭多边形还是开放路径等等[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值