CV图像处理小工具——json文件转P格式mask

CV图像处理小工具——json文件转P格式mask

import cv2
import json
import numpy as np
import os


def func(file_path: str) -> np.ndarray:
    try:
        with open(file_path, mode='r', encoding="utf-8") as f:
            configs = json.load(f)

            # 检查JSON是否包含必要的字段
        if "shapes" not in configs or "imageHeight" not in configs or "imageWidth" not in configs:
            raise ValueError("JSON文件缺少必要的字段")

        shapes = configs["shapes"]
        image_height = configs["imageHeight"]
        image_width = configs["imageWidth"]

        png = np.zeros((image_height, image_width, 3), np.uint8)

        for shape in shapes:
            if "points" not in shape:
                raise ValueError("形状缺少点信息")
            points = np.array(shape["points"], np.int32).reshape((-1, 1, 2))  # 确保点是正确的形状
            cv2.fillPoly(png, [points], (0, 0, 255))

        return png
    except Exception as e:
        print(f"处理文件 {file_path} 时出错: {e}")
        return None

    # 硬编码的文件路径


input_directory = "H:/"  # 可以是单个文件路径或目录路径
output_directory = "H:/"

# 确保输出目录存在
if not os.path.exists(output_directory):
    os.makedirs(output_directory)

# 处理单个文件或目录中的文件
if os.path.isfile(input_directory) and input_directory.endswith(".json"):
    # 处理单个JSON文件
    input_file = input_directory
    output_file = os.path.join(output_directory, os.path.splitext(os.path.basename(input_file))[0] + ".png")
    image = func(input_file)
    if image is not None:
        cv2.imwrite(output_file, image)
else:
    # 处理目录中的JSON文件
    for file_name in os.listdir(input_directory):
        if file_name.endswith(".json"):
            input_file = os.path.join(input_directory, file_name)
            output_file = os.path.join(output_directory, os.path.splitext(file_name)[0] + ".png")
            image = func(input_file)
            if image is not None:
                cv2.imwrite(output_file, image)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有梦想的炸豆皮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值