对图像分割的图片进行缩放的同时调整JSON标签

需要Imagedata字段版本

python 复制代码
import os
import json
import base64
from PIL import Image, ImageOps

# 原图目录
img_dir = r""

# 原 JSON 目录(修改标签前)
json_dir = r""

# 生成新的 resize 后图片目录
save_img_dir = r""

# 生成新的 JSON 目录(包含新的坐标 + imageData)
save_json_dir = r""

os.makedirs(save_img_dir, exist_ok=True)
os.makedirs(save_json_dir, exist_ok=True)

# 目标尺寸
target_w = 992
target_h = 992

img_exts = [".jpg", ".jpeg", ".png", ".bmp"]

for json_file in os.listdir(json_dir):

    if not json_file.endswith(".json"):
        continue

    json_name = os.path.splitext(json_file)[0]
    json_path = os.path.join(json_dir, json_file)

    # 尝试匹配图片
    matched_img_path = None
    for ext in img_exts:
        try_path = os.path.join(img_dir, json_name + ext)
        if os.path.exists(try_path):
            matched_img_path = try_path
            break

    if not matched_img_path:
        print("未找到对应图片:", json_name)
        continue

    # 读取 JSON(必须优先读取,因为它包含原始标注尺寸)
    with open(json_path, "r", encoding="utf-8") as f:
        data = json.load(f)

    ori_w = data["imageWidth"]
    ori_h = data["imageHeight"]

    # 缩放比例 = 新尺寸 ÷ JSON 原始标注尺寸
    scale_w = target_w / ori_w
    scale_h = target_h / ori_h

    # 打开图片(纠正 EXIF 旋转)
    img = Image.open(matched_img_path)
    img = ImageOps.exif_transpose(img)

    # resize 图片
    resized_img = img.resize((target_w, target_h), Image.LANCZOS)

    # 保存新图片
    new_img_path = os.path.join(save_img_dir, json_name + ".png")
    resized_img.save(new_img_path)

    # 更新 JSON 标签坐标
    for shape in data["shapes"]:
        new_points = []
        for x, y in shape["points"]:
            new_x = x * scale_w
            new_y = y * scale_h
            new_points.append([new_x, new_y])
        shape["points"] = new_points

    # 更新 JSON 的图像尺寸
    data["imageWidth"] = target_w
    data["imageHeight"] = target_h

    # 更新 imagePath(不带绝对路径)
    data["imagePath"] = os.path.basename(new_img_path)

    # 生成新的 base64 imageData
    with open(new_img_path, "rb") as f:
        image_data = base64.b64encode(f.read()).decode("utf-8")

    data["imageData"] = image_data

    # 保存新的 JSON(含坐标和 imageData)
    new_json_path = os.path.join(save_json_dir, json_name + ".json")
    with open(new_json_path, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

    print("已处理:", json_name)

print("全部完成!")

不需要imagedata字段版本

python 复制代码
import os
import json
from PIL import Image, ImageOps

# 输入路径
img_dir = r""
json_dir = r""

# 输出路径
save_img_dir = r""
save_json_dir = r""

os.makedirs(save_img_dir, exist_ok=True)
os.makedirs(save_json_dir, exist_ok=True)

# 目标尺寸
target_w = 992
target_h = 992

img_exts = [".jpg", ".jpeg", ".png"]

for img_file in os.listdir(img_dir):

    name, ext = os.path.splitext(img_file)
    if ext.lower() not in img_exts:
        continue

    img_path = os.path.join(img_dir, img_file)
    json_path = os.path.join(json_dir, name + ".json")

    if not os.path.exists(json_path):
        print("Warning: JSON not found for:", img_file)
        continue

    # 读取 JSON(必须先读 JSON,确保原始标注尺寸正确)
    with open(json_path, "r", encoding="utf-8") as f:
        data = json.load(f)

    ori_w = data["imageWidth"]
    ori_h = data["imageHeight"]

    # 坐标缩放比例必须基于 JSON 的尺寸,而不是图片本身!
    scale_w = target_w / ori_w
    scale_h = target_h / ori_h

    # 读取图片 + 修复 EXIF 旋转问题
    img = Image.open(img_path)
    img = ImageOps.exif_transpose(img)

    # resize 图片
    img_resized = img.resize((target_w, target_h), Image.LANCZOS)
    img_resized.save(os.path.join(save_img_dir, img_file))

    # 更新 JSON 内容
    data["imageWidth"] = target_w
    data["imageHeight"] = target_h
    data["imagePath"] = img_file  # 保持文件名即可,LabelMe 自动匹配
    data["imageData"] = None      # 防止 LabelMe 报错

    # 更新每个 shape 的坐标
    for shape in data["shapes"]:
        new_points = []
        for x, y in shape["points"]:
            new_x = x * scale_w
            new_y = y * scale_h
            new_points.append([new_x, new_y])
        shape["points"] = new_points

    # 保存新的 JSON
    with open(os.path.join(save_json_dir, name + ".json"), "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

    print("Processed:", img_file)

print("All done!")
相关推荐
KaneLogger2 小时前
【Agent】openclaw + opencode 打造助手 安装篇
人工智能·google·程序员
知识浅谈3 小时前
一步步带你把 OpenClaw 玩宕机(附云服务器避坑部署教程)
人工智能
冬奇Lab4 小时前
OpenClaw 深度解析(四):插件 SDK 与扩展开发机制
人工智能·开源·源码阅读
IT_陈寒5 小时前
SpringBoot实战:5个让你的API性能翻倍的隐藏技巧
前端·人工智能·后端
机器之心5 小时前
让AI自我进化?斯坦福华人博士答辩视频火了,庞若鸣参与评审
人工智能·openai
iceiceiceice5 小时前
iOS PDF阅读器段评实现:如何从 PDFSelection 精准还原一个自然段
前端·人工智能·ios
AI攻城狮6 小时前
RAG Chunking 为什么这么难?5 大挑战 + 最佳实践指南
人工智能·云原生·aigc
yiyu07167 小时前
3分钟搞懂深度学习AI:梯度下降:迷雾中的下山路
人工智能·深度学习
掘金安东尼7 小时前
玩转龙虾🦞,openclaw 核心命令行收藏(持续更新)v2026.3.2
人工智能