json 多目录合并

hebing_yaml.py
import os
import shutil
import time
import yaml
import json


class Time_Str:
    def __init__(self):
        self.last_time, self.counter = '', 0

    def get_time(self, fmt="%m%d_%H%M_%S"):
        now_time = time.strftime(fmt)
        self.counter += 1
        if now_time != self.last_time:
            self.last_time, self.counter = now_time, 0
        return f"{now_time}_{self.counter}"

    def get_time_sec(self):
        return self.get_time("%m%d_%H%M_%S")

    def get_time_mm(self):
        return self.get_time("%m%d_%H%M")


def update_json_image_path(json_path, new_img_name):
    """修改 JSON 文件中的 imagePath 字段"""
    try:
        with open(json_path, 'r', encoding='utf-8') as f:
            data = json.load(f)

        # 更新字段
        if "imagePath" in data:
            data["imagePath"] = new_img_name

        # 保存回原文件
        with open(json_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)
        print(f"✅ 更新 imagePath: {json_path} -> {new_img_name}")

    except Exception as e:
        print(f"⚠️ 修改 {json_path} 失败: {e}")


if __name__ == '__main__':
    name_get = Time_Str()
    yaml_path = r"data_chan.yaml"

    with open(yaml_path, 'r', encoding='utf-8') as f:
        data = yaml.safe_load(f)

    for key in ['train', 'val']:
        dirs = data[key]
        save_dir = rf"D:\data\det_chan_1112_{key}"
        os.makedirs(save_dir, exist_ok=True)

        for dir_a in dirs:
            json_files = [
                os.path.join(root, file).replace("\\", "/")
                for root, _, files in os.walk(dir_a)
                for file in files if file.lower().endswith(('.json', '.xpkl', '.xjpeg'))
            ]

            for json_file in json_files:
                json_name = os.path.basename(json_file)
                json_to = os.path.join(save_dir, json_name)
                img_path = os.path.splitext(json_file)[0] + ".jpg"

                if not os.path.exists(img_path):
                    print('❌ 图片不存在:', img_path)
                    continue

                if os.path.exists(json_to):
                    # 同名文件存在,重命名
                    new_name = name_get.get_time_mm()
                    json_name = f"{new_name}.json"
                    img_name = f"{new_name}.jpg"

                    new_json_path = os.path.join(save_dir, json_name)
                    new_img_path = os.path.join(save_dir, img_name)

                    shutil.copyfile(json_file, new_json_path)
                    shutil.copyfile(img_path, new_img_path)

                    # 修改 imagePath
                    update_json_image_path(new_json_path, img_name)
                else:
                    # 不重名,直接复制
                    shutil.copy(json_file, save_dir)
                    shutil.copy(img_path, save_dir)

    print("\n训练集路径(train):", data['train'])
    print("验证集路径(val):", data['val'])
    print("类别数(nc):", data['nc'])
    print("类别名称(names):", data['names'])

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI算法网奇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值