import json import cv2 import os from pathlib import Path # ==================== 你只需要改这 1 个路径 ==================== LABEL_FOLDER = "篆文pic" # 放 json 和原图的文件夹(必须同目录) OUTPUT_FOLDER = "chars" # 切割后输出的文件夹 # =============================================================== Path(OUTPUT_FOLDER).mkdir(exist_ok=True) def imread_unicode(path): return cv2.imdecode(np.fromfile(path, dtype=np.uint8), cv2.IMREAD_COLOR) def imwrite_unicode(path, img): cv2.imencode('.png', img)[1].tofile(path) def cut_labels(json_path): # 读取标注 with open(json_path, 'r', encoding='utf-8') as f: data = json.load(f) # 原图路径 img_path = os.path.join(os.path.dirname(json_path), data['imagePath']) img = imread_unicode(img_path) if img is None: print(f"找不到图片:{img_path}") return # 文件名前缀 prefix = Path(data['imagePath']).stem # 遍历每个框 idx = 0 for shape in data['shapes']: points = shape['points'] label = shape['label'] # 坐标转整数 x1 = int(min(p[0] for p in points)) y1 = int(min(p[1] for p in points)) x2 = int(max(p[0] for p in points)) y2 = int(max(p[1] for p in points)) # 切割 crop = img[y1:y2, x1:x2] # 保存 save_name = f"{prefix}_{label}_{idx:02d}.png" save_path = os.path.join(OUTPUT_FOLDER, save_name) imwrite_unicode(save_path, crop) idx += 1 print(f"✅ 已切割:{img_path} → {idx} 个字") if __name__ == "__main__": import numpy as np json_files = list(Path(LABEL_FOLDER).glob("*.json")) for jf in json_files: cut_labels(jf) print("\n🎉 全部切割完成!输出在:", OUTPUT_FOLDER)