对图像分割的图片进行缩放的同时调整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!")
相关推荐
千寻girling4 分钟前
不知道 Java 全栈 + AI 编程有没有搞头 ?
前端·人工智能·后端
君科程序定做7 分钟前
多源遥感与深度学习视角下耕地识别与耕地监测的局限性、研究空白与科学问题
人工智能·深度学习
七夜zippoe7 分钟前
可解释AI:构建可信的机器学习系统——反事实解释与概念激活实战
人工智能·python·机器学习·可解释性·概念激活
东离与糖宝13 分钟前
Java 26+Spring Boot 3.5,微服务启动从3秒压到0.8秒
java·人工智能
Daydream.V25 分钟前
OpenCV高端操作——光流估计(附案例)
人工智能·opencv·计算机视觉
冬奇Lab1 小时前
一天一个开源项目(第60篇):IndexTTS - B 站开源的工业级零样本语音合成系统
人工智能·开源·资讯
子兮曰1 小时前
🚀Hermes Agent 爆火真相:19k Star 背后的自学习 Agent 系统
人工智能·agent
AI先驱体验官2 小时前
智能体变现:从技术实现到产品化的实践路径
大数据·人工智能·深度学习·重构·aigc
大连好光景2 小时前
软件测试笔记(2)
人工智能·功能测试·模块测试
纪伊路上盛名在2 小时前
机器学习中的固定随机种子方案
人工智能·机器学习·数据分析·随机种子