import os
import shutil
import json

# 设置路径
src_root = "../MRI_7_20_v3"
dst_data_dir = "yolodata"
os.makedirs(dst_data_dir, exist_ok=True)

# 遍历所有目录和文件
for subdir, dirs, files in os.walk(src_root):
    for file in files:
        if file.endswith(".json"):
            json_path = os.path.join(subdir, file)
            png_path = os.path.join(subdir, file.replace(".json", ".png"))

            try:
                with open(json_path, 'r', encoding='utf-8') as f:
                    data = json.load(f)

                # 判断 shapes 字段是否为空
                if "shapes" in data and data["shapes"]:
                    # 有标注，复制 json 和 png

                    # 复制 json
                    dst_json = os.path.join(dst_data_dir, file)
                    json_base, json_ext = os.path.splitext(file)
                    counter = 1
                    while os.path.exists(dst_json):
                        dst_json = os.path.join(dst_data_dir, f"{json_base}_{counter}{json_ext}")
                        counter += 1
                    shutil.copy2(json_path, dst_json)
                    print(f"Copied: {json_path} -> {dst_json}")

                    # 复制对应 png
                    if os.path.exists(png_path):
                        dst_png = os.path.join(dst_data_dir, os.path.basename(png_path))
                        png_base, png_ext = os.path.splitext(os.path.basename(png_path))
                        counter = 1
                        while os.path.exists(dst_png):
                            dst_png = os.path.join(dst_data_dir, f"{png_base}_{counter}{png_ext}")
                            counter += 1
                        shutil.copy2(png_path, dst_png)
                        print(f"Copied: {png_path} -> {dst_png}")
                    else:
                        print(f"[Warning] PNG not found for: {json_path}")

                else:
                    print(f"Skipped (empty shapes): {json_path}")

            except Exception as e:
                print(f"[Error] Failed to process {json_path}: {e}")


