CV图像处理小工具——语义分割json生成检测框json

语义分割json生成检测框json

python 复制代码
import json
import os
from os import listdir, getcwd
from os.path import join
import os.path


rootdir = 'F:/dataset/'# 写自己存放图片的数据地址
input_dir = 'F:/dataset/labels_json/'
output_dir = 'F:/dataset/labels_box/'
def position(pos):
    # 该函数用来找出xmin,ymin,xmax,ymax即bbox包围框
    x = []
    y = []
    nums = len(pos)
    for i in range(nums):
        x.append(pos[i][0])
        y.append(pos[i][1])
    x_max = max(x)
    x_min = min(x)
    y_max = max(y)
    y_min = min(y)
    b = (float(x_min), float(x_max), float(y_min), float(y_max))
    return b




def convert_annotation(image_ids, input_dir, output_dir):
    for image_id in image_ids:
        print(image_id)
        input_file_path = os.path.join(input_dir, f"{image_id}.json")
        output_file_path = os.path.join(output_dir, f"{image_id}.json")

        try:
            with open(input_file_path, 'r') as load_f:
                load_dict = json.load(load_f)

            w = load_dict['imageWidth']
            h = load_dict['imageHeight']
            objects = load_dict['shapes']

            annotations = []  # 创建一个空列表来存储注解

            for obj in objects:
                # 去除可能的额外空格,并设置默认标签(如果需要)
                labels = obj['label'].strip()
                # 根据标签处理形状
                if labels in [
                    "class1", "class2",
                    "class3", "class4"
                ]:
                    pos = obj['points']
                    b = position(pos)
                    cls_id_mapping = {
                        "class1": 1,
                        "class2": 2,
                        "class3": 3,
                        "class4": 4,
                        
                    }
                    cls_id = cls_id_mapping[labels]
                    annotation = {
                        'label': labels,
                        'class_id': cls_id,
                        'bbox': b
                    }
                    annotations.append(annotation)

            output_dict = {
                "version": "5.0.2",
                "flags": {},
                "shapes": [],  # shapes数组为空,因为注解信息已经放在annotations中
                "imagePath": load_dict['imagePath'],
                "imageData": None,
                "imageHeight": h,
                "imageWidth": w,
                "annotations": annotations  # 添加注解列表
            }
            for shape in load_dict['shapes']:
                # 假设每个多边形都有四个点,我们可以直接取对角线上的两个点来定义矩形
                # 这里我们取第一个点和第三个点(或者您可以根据具体情况选择其他点对)
                objects = load_dict['shapes']
                for obj in objects:
                    # 去除可能的额外空格,并设置默认标签(如果需要)
                    labels = obj['label'].strip()
                    if labels in [
                       "class1", "class2",
                    "class3", "class4"
                    ]:
                        pos = obj['points']
                        b = position(pos)
                        rect_points = [
                            [b[0], b[3]],
                            [b[1], b[2]]
                            ]

                        new_shape = {
                        "label": labels,  # 保留原多边形的标签(或者您可以根据需要生成新的标签)
                        "points": rect_points,  # 使用调整后的点来表示矩形(但这里我们实际上只使用了两个点)
                        # 注意:由于我们简化了问题,并没有真正地使用四个点来定义一个完整的矩形
                        # 在实际应用中,您可能需要更精确地处理这个问题。
                        "group_id": None,  # 您可以根据需要设置这个字段的值
                        "shape_type": "rectangle",  # 指定形状类型为矩形
                        "flags": {}  # 保留空的flags字段(或者您可以根据需要填充它)
                    }
                        output_dict['shapes'].append(new_shape)

                # 写入新的JSON文件
            with open(output_file_path, 'w') as output_f:
                json.dump(output_dict, output_f, indent=4)

        except Exception as e:
            print(f"Error processing {input_file_path}: {e}")


def image_id(rootdir):
    a = []
    for parent, dirnames, filenames in os.walk(rootdir):
        for filename in filenames:
            # print(filename)
            if filename.endswith('.jpg'):
                filename = os.path.splitext(filename)[0]
            if filename.endswith('.jpeg'):
                filename = os.path.splitext(filename)[0]
            if filename.endswith('.JPG'):
                filename = os.path.splitext(filename)[0]
            if filename.endswith('.JPEG'):
                filename = os.path.splitext(filename)[0]
            a.append(filename)
    return a


names = image_id("F:/dataset/images/"),

for image_id in names:
    convert_annotation(image_id, input_dir, output_dir)
相关推荐
日常通勤穿搭32 分钟前
电商 AI 生图工具横评|AI 生成主图、详情套图工具哪家性价比高
人工智能·aigc·电商美工
Ai_easygo1 小时前
AI下半场_06_CSDN版_开源AI最后一公里
人工智能
jimmyleeee1 小时前
大模型安全之十五:AI Access Control:当“门禁”遇上会思考的系统
人工智能·安全
HIT_Weston1 小时前
224、【AI】【模型部署】基座模型研究:Qwen2 架构总览与 config 对照
人工智能·模型部署
我叫张土豆1 小时前
本体论、DDD、SDD、TDD:AI 编程时代的四层认知栈
java·人工智能
蓝速科技1 小时前
便民服务大厅 AI 数字人一体机场景适配与落地指南丨蓝速科技
大数据·网络·数据结构·人工智能·自然语言处理·数据分析·运维开发
IT_陈寒1 小时前
Vue的响应式更新把我坑惨了,原来问题出在这
前端·人工智能·后端
深圳市青牛科技实业有限公司 小芋圆2 小时前
GC1808:高性能、低成本的立体声音频ADC芯片
人工智能·嵌入式硬件·无人机·太阳能逆变器
龙腾AI白云2 小时前
孪生不止在工厂:能源、医疗与农业
人工智能·机器学习·scikit-learn·知识图谱
精益数智工坊2 小时前
云计算环境数据怎么同步?云计算集成方案有哪些?
大数据·人工智能·数据挖掘·数据可视化