对图像分割的图片进行缩放的同时调整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!")
相关推荐
h64648564h13 分钟前
CANN 性能剖析与调优全指南:从 Profiling 到 Kernel 级优化
人工智能·深度学习
数据与后端架构提升之路14 分钟前
论系统安全架构设计及其应用(基于AI大模型项目)
人工智能·安全·系统安全
忆~遂愿18 分钟前
ops-cv 算子库深度解析:面向视觉任务的硬件优化与数据布局(NCHW/NHWC)策略
java·大数据·linux·人工智能
Liue6123123122 分钟前
YOLO11-C3k2-MBRConv3改进提升金属表面缺陷检测与分类性能_焊接裂纹气孔飞溅物焊接线识别
人工智能·分类·数据挖掘
一切尽在,你来30 分钟前
第二章 预告内容
人工智能·langchain·ai编程
23遇见34 分钟前
基于 CANN 框架的 AI 加速:ops-nn 仓库的关键技术解读
人工智能
Codebee43 分钟前
OoderAgent 企业版 2.0 发布的意义:一次生态战略的全面升级
人工智能
光泽雨1 小时前
检测阈值 匹配阈值分析 金字塔
图像处理·人工智能·计算机视觉·机器视觉·smart3
Σίσυφος19001 小时前
PCL 法向量估计-PCA邻域点(经典 kNN 协方差)的协方差矩阵
人工智能·线性代数·矩阵
小鸡吃米…2 小时前
机器学习的商业化变现
人工智能·机器学习