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:调整转换框的大小