当前位置: 首页 > article >正文

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

CV图像处理小工具——json文件转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)

在这里插入图片描述


http://www.kler.cn/news/353394.html

相关文章:

  • 十一、数据库配置
  • QT 实现按钮多样化
  • 企业级 RAG 全链路优化关键技术
  • 【不要离开你的舒适圈】:猛兽才希望你落单,亲人总让你回家,4个维度全面构建舒适圈矩阵
  • 6-2.Android 对话框之基础对话框问题清单(UI 线程问题、外部取消、冲突问题、dismiss 方法与 hide 方法)
  • redis 创建只读用户
  • 06_实现watch
  • 【排序】——2.快速排序法(含优化)
  • 开源项目低代码表单FormCreate重写内置的请求方法,实现中间件和附带token
  • 类间方差,分割地物
  • 基于SSM的医院药品管理系统
  • 【人工智能-初级】第2章 机器学习入门:从线性回归开始
  • 【C语言】文件、结构体综合应用:小型学生成绩管理
  • Qt:图片文字转base64程序
  • 云栖实录 | 智能运维年度重磅发布及大模型实践解读
  • Docker配置网站环境
  • Redis 消息队列:实现、操作与性能优化
  • 【SSM详细教程】-01-Spring容器以及配置详解
  • C#从零开始学习(Head First C#)
  • 【论文阅读笔记】The Chubby lock service for loosely-coupled distributed systems
  • Spring Boot环境下的大创项目协作工具
  • 2024ideaUI切换和svn与git的切换
  • Floyd
  • 文本语义检索系统的搭建过程,涵盖了召回、排序以及Milvus召回系统、短视频推荐等相关内容
  • C++ | Leetcode C++题解之第476题数字的补数
  • ThinkPHP 3.2 + Nginx 页面404问题