json缩放 json 缩放
目录
Labelme JSON
json缩放
Labelme JSON
{"version": "5.3.1","flags": {},"imageData": null,"imageHeight": 1080,"imageWidth": 1920,"imagePath": "first_frame.jpg","shapes": [{"label": "1","points": [[870,337],[1213,704]],"group_id": 0,"description": "","shape_type": "rectangle","flags": {}}]
}
json缩放
import json
import copy
import osimport cv2
import numpy as npdef save_rescaled_json(annotation: dict, output_path: str, scale: float):# 深拷贝原始标注,避免修改原对象new_anno = copy.deepcopy(annotation)# 更新图片宽高if "imageHeight" in new_anno:new_anno["imageHeight"] = int(round(new_anno["imageHeight"] * scale))if "imageWidth" in new_anno:new_anno["imageWidth"] = int(round(new_anno["imageWidth"] * scale))# 遍历 shapes 并缩放每个点for shape in new_anno.get("shapes", []):if "points" in shape:pts = np.array(shape["points"], dtype=np.float32)pts *= scaleshape["points"] = pts.tolist()# 保存文件os.makedirs(os.path.dirname(output_path), exist_ok=True)with open(output_path, "w", encoding="utf-8") as f:json.dump(new_anno, f, ensure_ascii=False, indent=2)print(f"✅ 已保存缩放后的标注:{output_path}")if __name__ == '__main__':img_path=r"D:\data\tmp\data_similar\sample\box_frame.jpg"splits=os.path.splitext(img_path)save_path=splits[0]+"_scale.jpg"json_path=splits[0]+".json"json_path_new=splits[0]+"_scale.json"# 1. 读取原始标注with open(json_path, "r", encoding="utf-8") as f:anno = json.load(f)scale=0.5anno['imagePath']=save_path# 2. 缩放并保存save_rescaled_json(anno, json_path_new, scale=scale)img=cv2.imread(img_path)h,w=img.shape[:2]new_w = int(w * scale)new_h = int(h * scale)img_new = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_LINEAR)cv2.imwrite(save_path, img_new)
