labelme的一个特定标签改成另一个标签

Python代码

点击查看代码
import json
import os
from pathlib import Path

# 把labelme的一个特定标签改成另一个标签
def replace_labelme_label(
        input_path: str,
        old_label: str,
        new_label: str,
        output_path: str = None,
        overwrite: bool = False
):
    """
    修改 LabelMe 标注 JSON 文件中的指定标签

    Args:
        input_path: 输入的 LabelMe JSON 文件路径
        old_label: 要替换的旧标签(如 "cat")
        new_label: 替换后的新标签(如 "dog")
        output_path: 输出文件路径(None 则默认覆盖/另存为原文件名+_modified)
        overwrite: 是否直接覆盖原文件(仅当 output_path 为 None 时生效)
    """
    # 校验输入文件是否存在
    if not os.path.exists(input_path):
        raise FileNotFoundError(f"文件不存在:{input_path}")

    # 读取 JSON 文件
    with open(input_path, 'r', encoding='utf-8') as f:
        data = json.load(f)

    # 统计替换数量
    replace_count = 0

    # 遍历所有标注形状,修改标签
    for shape in data.get('shapes', []):
        if shape.get('label') == old_label:
            shape['label'] = new_label
            replace_count += 1

    # 确定输出路径
    if output_path is None:
        if overwrite:
            output_path = input_path
        else:
            # 另存为:原文件名_modified.json
            path = Path(input_path)
            output_path = str(path.parent / f"{path.stem}_modified{path.suffix}")

    # 保存修改后的 JSON
    with open(output_path, 'w', encoding='utf-8') as f:
        # ensure_ascii=False 避免中文标签乱码,indent 保持格式美观
        json.dump(data, f, ensure_ascii=False, indent=2)

    print(f"处理完成!文件:{input_path}")
    print(f"共替换 {replace_count} 个 '{old_label}' 标签为 '{new_label}'")
    print(f"结果保存至:{output_path}\n")


def batch_replace_labels(
        input_dir: str,
        old_label: str,
        new_label: str,
        overwrite: bool = False
):
    """
    批量处理指定目录下所有 LabelMe JSON 标注文件

    Args:
        input_dir: 存放 JSON 文件的目录
        old_label: 要替换的旧标签
        new_label: 替换后的新标签
        overwrite: 是否直接覆盖原文件
    """
    # 遍历目录下所有 .json 文件
    for file_name in os.listdir(input_dir):
        if file_name.endswith('.json'):
            input_path = os.path.join(input_dir, file_name)
            replace_labelme_label(
                input_path=input_path,
                old_label=old_label,
                new_label=new_label,
                overwrite=overwrite
            )


# ------------------- 示例使用 -------------------
if __name__ == "__main__":
    # 示例1:处理单个文件(不覆盖原文件,另存为新文件)
    # replace_labelme_label(
    #     input_path="test_labelme.json",  # 你的标注文件路径
    #     old_label="旧标签",  # 要替换的标签(比如 "car")
    #     new_label="新标签"  # 替换后的标签(比如 "vehicle")
    # )

    # 示例2:处理单个文件(直接覆盖原文件)
    # replace_labelme_label(
    #     input_path="test_labelme.json",
    #     old_label="car",
    #     new_label="vehicle",
    #     overwrite=True
    # )

    # 示例3:批量处理目录下所有 JSON 文件(不覆盖原文件)
    batch_replace_labels(
        input_dir=r"D:\pic\Guangzhoumeiwei\single_mangkong0922new_arrived\rightpixel20260108JoinLabel\src",  # 标注文件所在目录
        old_label="tag4",
        new_label="tag2",
        overwrite=True
    )
posted @ 2026-01-21 17:30  阳光天气  阅读(0)  评论(0)    收藏  举报