Python实现利用仅有像素级标注的json文件生成框标注的json文件,并存放到新文件夹

Python脚本:根据多边形标签创建矩形标注并转换JSON文件
import json
import os
# create rectangle labels based on polygon labels, and store in a new folder
def create_rectangle_shapes(polygon_shapes):
    rectangle_shapes = []
    for polygon_shape in polygon_shapes:
        # 获取多边形的坐标点
        points = polygon_shape['points']
        # 找到最左上角和最右下角的坐标
        left = min(points, key=lambda x: x[0])[0]
        bottom = min(points, key=lambda x: x[1])[1]
        right = max(points, key=lambda x: x[0])[0]
        top = max(points, key=lambda x: x[1])[1]
        # 创建新的矩形形状
        rectangle_shape = {
            "label": polygon_shape['label'],
            "points": [
                [left, bottom],
                [right, top],
            ],
            "group_id": polygon_shape['group_id'],
            "shape_type": "rectangle",
            "flags": polygon_shape['flags']
        }
        rectangle_shapes.append(rectangle_shape)
    return rectangle_shapes

def main(json_file, target_file):
    # 读取原始JSON文件
    with open(json_file, 'r', encoding='utf-8') as f:
        data = json.load(f)

    # 删除所有shape_type为rectangle的标注
    data['shapes'] = [shape for shape in data['shapes'] if shape['shape_type'] != 'rectangle']

    # 生成新的shape_type为rectangle的标注
    rectangle_shapes = create_rectangle_shapes(data['shapes'])

    # 将新的矩形形状添加到原始数据中
    data['shapes'].extend(rectangle_shapes)

    # 创建输出文件夹
    # output_dir = r'D:\dataset\dataset\1_seg_rect'
    # if not os.path.exists(output_dir):
    #     os.makedirs(output_dir)

    # 保存新的JSON文件
    # with open(os.path.join(output_dir, r'20231016-105404-812_9.json'), 'w') as f:
    with open(target_file, 'w') as f:
        json.dump(data, f, indent=4)

# 运行脚本
if __name__ == "__main__":
    jsonF = []
    newF = []
    for i in range(1,7):  # 此处替换文件目录地址
        json_folder = r'D:\dataset\dataset'  # 存放json文件的目录
        new_folder = r"D:\dataset\dataset"  # 存放新json文件的目录
        json_folder += '\\' + str(i) + '_seg_without_rect'
        new_folder += '\\' + str(i) + '_seg_rect'
        if os.path.exists(json_folder):
            jsonF.append(json_folder)
            newF.append(new_folder)
            if not os.path.exists(new_folder):
                os.makedirs(new_folder)
        else:
            print("not found file")
    for i in range(len(jsonF)):
        for filename in os.listdir(jsonF[i]):
            if filename.split(".")[-1]=="json":
                f = os.path.join(jsonF[i], filename)
                o = os.path.join(newF[i], filename)
                
                main(f,o)
                print(f+" completed")

文件目录结构如图:

在这里插入图片描述

要将Labelme标注图片文件夹生成JSON文件导入Python调用,可以利用Python的`json`模块来实现。以下是详细步骤及示例代码: ### 1. 导入必要的库 使用`json`模块来处理JSON数据,`os`模块用于文件和目录操作。 ```python import json import os ``` ### 2. 遍历包含JSON文件文件夹 使用`os.listdir()`函数遍历指定文件夹中的所有文件筛选出扩展名为`.json`的文件。 ```python json_folder = 'path/to/your/json/folder' # 替换为实际的JSON文件夹路径 json_files = [f for f in os.listdir(json_folder) if f.endswith('.json')] ``` ### 3. 读取解析JSON文件 使用`open()`函数打开JSON文件,然后使用`json.load()`函数将其解析为Python字典。 ```python for json_file in json_files: json_path = os.path.join(json_folder, json_file) with open(json_path, 'r', encoding='utf-8') as file: data = json.load(file) # 在这里可以对解析后的JSON数据进行操作 print(data) ``` ### 完整示例代码 ```python import json import os json_folder = 'path/to/your/json/folder' # 替换为实际的JSON文件夹路径 json_files = [f for f in os.listdir(json_folder) if f.endswith('.json')] for json_file in json_files: json_path = os.path.join(json_folder, json_file) with open(json_path, 'r', encoding='utf-8') as file: data = json.load(file) # 在这里可以对解析后的JSON数据进行操作 print(data) ``` 通过以上步骤,就可以将Labelme标注图片文件夹生成JSON文件导入Python进行调用。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Env1sage

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

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

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

打赏作者

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

抵扣说明:

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

余额充值