labelme标注后的图片和json同步resize
见代码
点击查看代码
import cv2
import os
import numpy as np
import base64
import json
import shutil
# labelme标注后的图片和json同步resize
in_dir = r'D:\pic\2024demo03\big_to_resize' #标注数据集地址
output_dir = r"D:\pic\2024demo03\big_resized" #输出地址 输出地址中需放入原始图片,不用放json
img_list = [f for f in os.listdir(in_dir) if f.endswith(".PNG")]
if not os.path.exists(output_dir):
os.makedirs(output_dir, exist_ok=True)
for img_name in img_list:
json_name = img_name.replace(".PNG", ".json")
img = cv2.imread(os.path.join(in_dir, img_name))
h, w = img.shape[:2]
# resize尺寸根据自己需求调整
re_size = (1024, 1024)
img_re = cv2.resize(img, re_size)
img_path = os.path.join(output_dir, img_name)
cv2.imwrite(img_path, img_re)
# resize json
re_x = re_size[0] / w
re_y = re_size[1] / h
with open(os.path.join(in_dir, json_name), "r", encoding="utf-8") as f:
data = json.load(f)
shapes = data["shapes"]
for shape in shapes:
points = shape["points"]
for i, pt in enumerate(points):
pt = [pt[0] * re_x, pt[1] * re_y]
points[i] = pt
shape["points"] = points
data["shapes"] = shapes
data["imagePath"] = img_name
with open(img_path, "rb") as h:
data["imageData"] = base64.b64encode(h.read()).decode('utf-8')
img = cv2.imread(img_path)
data["imageHeight"], data["imageWidth"] = re_size[1], re_size[0]
# save the new json file
json_out = os.path.join(output_dir, json_name)
with open(json_out, "w", encoding="UTF-8") as f1:
json.dump(data, f1, ensure_ascii=False, indent=2)
print(f"json_path edited!:{json_out}")