对图像分割的图片进行缩放的同时调整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!")
相关推荐
传说故事2 分钟前
【论文自动阅读】视频生成模型的Inference-time物理对齐 with Latent World Model
人工智能·深度学习·音视频·视频生成
半臻(火白)2 分钟前
Clawbot:重新定义AI的「行动派」革命
人工智能
造夢先森4 分钟前
Clawdbot(OpenClaw)安装部署教程
人工智能·微服务·云原生
攻城狮7号5 分钟前
宇树 开源 UnifoLM-VLA-0 大模型:给人形机器人装上通用的“直觉大脑”
人工智能·机器人·具身智能·宇树科技·unifolm-vla-0
aihuangwu9 分钟前
ChatGPT和Gemini图表怎么导出
人工智能·ai·chatgpt·deepseek·ds随心转
Bits to Atoms13 分钟前
宇树G1语音助手完整开发指南(下)——从零构建智能知识库对话系统
人工智能·机器人·音视频·语音识别
Katecat9966329 分钟前
古巽伽罗语字符识别与分类_Cascade-Mask-RCNN_RegNetX-400MF实现
人工智能·目标跟踪
说文科技32 分钟前
大模型项目实战之dpo微调
人工智能·算法
周杰伦_Jay38 分钟前
【Mac 上命令行安装 Claude Code】(Claude 的终端版 AI 编程助手)完整指南
人工智能·macos·claude code
一只理智恩43 分钟前
AI辅助,两天实现一个IM系统?
人工智能