对图像分割的图片进行缩放的同时调整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!")
相关推荐
kaizq6 分钟前
大语言模型典型本地搭建及其应用
人工智能·ollama·cherry studio·文本对话聊天·知识库/代码库·mcp服务编制·大语言模型llm本地应用
wenzhangli79 分钟前
2025软件行业寒冬突围:破解AI编程冲击与项目制困局,一拖三闭环方案成破局关键
人工智能·ai编程
汽车仪器仪表相关领域11 分钟前
全自动化精准检测,赋能高效年检——NHD-6108全自动远、近光检测仪项目实战分享
大数据·人工智能·功能测试·算法·安全·自动化·压力测试
夜雨深秋来13 分钟前
都2026年了你还不知道AI工程化!
人工智能·代码规范
●VON15 分钟前
AI 伦理治理实操指南:从原则到生产线
人工智能
星浩AI22 分钟前
Google 官方发布:让你的 AI 编程助手"边写、边看、边调",像人类开发者一样工作
人工智能·后端·开源
Codebee44 分钟前
SkillFlow:回归本质的AI能力流程管控
人工智能
巫山老妖1 小时前
2026 年 AI 趋势深度研究报告
人工智能
CodeLove·逻辑情感实验室1 小时前
深度解析:当 NLP 试图解构爱情——情感计算(Affective Computing)的伦理边界与技术瓶颈
人工智能·深度学习·自然语言处理·赛朋克
少林码僧2 小时前
2.9 字段分箱技术详解:连续变量离散化,提升模型效果的关键步骤
人工智能·ai·数据分析·大模型