标签拷贝 labelme json格式

label_copy.py

python 复制代码
import glob
import json
import os

from natsort import natsorted


def copy_labels_from_a_to_b(labels_to_copy, a_file='a.json', b_file='b.json'):
    """
    从 a.json 中复制多个标签到 b.json

    参数:
    labels_to_copy: 要复制的标签名称列表
    a_file: 源文件路径
    b_file: 目标文件路径
    """
    try:
        # 读取源文件
        with open(a_file, 'r', encoding='utf-8') as f:
            data_a = json.load(f)

        # 读取目标文件
        with open(b_file, 'r', encoding='utf-8') as f:
            data_b = json.load(f)

        # 确保 b.json 中有 shapes 列表
        if 'shapes' not in data_b:
            data_b['shapes'] = []

        total_copied = 0
        # 查找并复制所有匹配的标签
        for label in labels_to_copy:
            shapes_to_copy = []
            for shape in data_a.get('shapes', []):
                if shape.get('label') == label:
                    shape_copy = shape.copy()
                    shapes_to_copy.append(shape_copy)

            if shapes_to_copy:
                data_b['shapes'].extend(shapes_to_copy)
                total_copied += len(shapes_to_copy)
                print(f"找到并复制 {len(shapes_to_copy)} 个 '{label}' 标签")

        if total_copied > 0:
            # 保存更新后的文件
            with open(b_file, 'w', encoding='utf-8') as f:
                json.dump(data_b, f, indent=4, ensure_ascii=False)

            print(f"总计复制 {total_copied} 个标签到 {b_file}")
        else:
            print(f"在 {a_file} 中未找到指定的任何标签: {labels_to_copy}")

        return total_copied

    except Exception as e:
        print(f"发生错误: {e}")
        return 0

# 使用示例
if __name__ == "__main__":
    # 复制单个标签
    # copy_labels_from_a_to_b(['zhi'])

    to_base=r"D:\data\jiezhi\det_1201\1201"

    dirs=glob.glob(os.path.join(to_base, "*"))
    dirs=[r"D:\data\jiezhi\det_1201\1201\20251201-201937"]

    for to_dir in dirs:

        dir_name=os.path.basename(to_dir)
        from_dir=rf"D:\data\jiezhi\det_1201\zhi_from\{dir_name}"

        json_from=glob.glob(os.path.join(from_dir, "*.json"))

        json_from=natsorted(json_from)


        json_to=glob.glob(os.path.join(to_dir, "*.json"))

        json_to=natsorted(json_to)

        for json_i, json_file in enumerate(json_from[:len(json_to)]):

            json_to_path=json_to[json_i]

            # 复制多个标签
            copy_labels_from_a_to_b(['zhi'],a_file=json_file,b_file=json_to_path)
            print(json_to_path)
相关推荐
多米Domi01120 小时前
0x3f第33天复习 (16;45-18:00)
数据结构·python·算法·leetcode·链表
罗湖老棍子21 小时前
【例4-11】最短网络(agrinet)(信息学奥赛一本通- P1350)
算法·图论·kruskal·prim
方圆工作室21 小时前
【C语言图形学】用*号绘制完美圆的三种算法详解与实现【AI】
c语言·开发语言·算法
Lips61121 小时前
2026.1.16力扣刷题
数据结构·算法·leetcode
kylezhao20191 天前
C# 文件的输入与输出(I/O)详解
java·算法·c#
这张生成的图像能检测吗1 天前
(论文速读)轴向变压器
人工智能·计算机视觉·注意力机制
CodeByV1 天前
【算法题】堆
算法
pythonpapaxia1 天前
基于Matlab的车牌识别完整教程:从图像预处理到字符识别实战解析
图像处理·其他·计算机视觉·matlab
kaikaile19951 天前
A星算法避开障碍物寻找最优路径(MATLAB实现)
数据结构·算法·matlab
今天_也很困1 天前
LeetCode 热题100-15.三数之和
数据结构·算法·leetcode