批量将点标注(.json)转换成框标注(.json)

import json
import os
import shutil


def convert_points_to_boxes(points_data, box_size=40):
    shapes = []
    for point in points_data['shapes']:
        label = point['label']
        x, y = point['points'][0]  # Extracting the coordinates of the point

        # Calculating the coordinates for the bounding box
        x1 = x - box_size // 2
        y1 = y - box_size // 2
        x2 = x + box_size // 2
        y2 = y + box_size // 2

        # Creating the box annotation
        box_annotation = {
            "label": label,
            "points": [
                [x1, y1],
                [x2, y2]
            ],
            "group_id": None,
            "description": "",
            "shape_type": "rectangle",
            "flags": {}
        }

        shapes.append(box_annotation)

    # Creating a new JSON structure with box annotations
    boxes_json = {
        "version": points_data['version'],
        "flags": points_data['flags'],
        "shapes": shapes,
        "imagePath": points_data['imagePath'],
        "imageData": points_data['imageData'],
        "imageHeight": points_data['imageHeight'],
        "imageWidth": points_data['imageWidth']
    }

    return boxes_json


# Directory containing the point annotation JSON files
points_dir = 'points'

# Directory to save the resulting box annotation JSON files
boxes_dir = 'rectangles'

# Create a new directory to save box annotation JSON files
os.makedirs(boxes_dir, exist_ok=True)

# Process each JSON file in the directory
for filename in os.listdir(points_dir):
    if filename.endswith('.json'):
        file_path = os.path.join(points_dir, filename)
        with open(file_path, 'r', encoding='utf-8') as file:  # Specify encoding
            points_data = json.load(file)

        # Convert points to boxes
        boxes_data = convert_points_to_boxes(points_data)

        # Save the resulting JSON with box annotations in the new directory
        output_path = os.path.join(boxes_dir, filename)
        with open(output_path, 'w', encoding='utf-8') as output_file:  # Specify encoding
            json.dump(boxes_data, output_file, indent=2, ensure_ascii=False)  # Disable ASCII encoding

points_dir : 点标注目录
boxes_dir :框标注目录
box_size:调整转换框的大小

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值