圆形转矩形框
import json
import os
def calculate_bounding_square(circle, image_width, image_height):
x, y = circle['points'][0]
radius = circle['points'][1][0] - x
# 半径至少为20,以保证最小边长至少为40
if radius < 20:
radius = 20
elif radius > 40: # 如果半径超过40,则设置半径为40
radius = 36
side_length = radius * 2
# 再次检查,确保生成的正方形边长至少为40
if side_length < 40:
side_length = 40
radius = side_length / 2
# 计算正方形的左上角和右下角坐标
top_left_x = max(x - radius, 0)
top_left_y = max(y - radius, 0)
bottom_right_x = min(x + radius, image_width)
bottom_right_y = min(y + radius, image_height)
# 返回正方形的详细信息
return {
"label": circle["label"],
"points": [[top_left_x, top_left_y], [bottom_right_x, bottom_right_y]],
"group_id": circle["group_id"],
"shape_type": "rectangle",
"flags": circle["flags"]
}
def convert_circle_to_bounding_square(circle, image_width, image_height):
return calculate_bounding_square(circle, image_width, image_height)
def convert_json_shapes(json_data, image_width, image_height):
new_shapes = []
for shape in json_data["shapes"]:
if shape["shape_type"] == "circle":
new_shapes.append(convert_circle_to_bounding_square(shape, image_width, image_height))
else:
new_shapes.append(shape)
json_data["shapes"] = new_shapes
def process_json_file(file_path):
with open(file_path, 'r') as f:
json_data = json.load(f)
convert_json_shapes(json_data, json_data["imageWidth"], json_data["imageHeight"])
with open(file_path, 'w') as f:
json.dump(json_data, f, indent=4)
def process_json_files_in_directory(directory):
for filename in os.listdir(directory):
if filename.endswith('.json'):
file_path = os.path.join(directory, filename)
process_json_file(file_path)
# 替换为你的文件夹路径
directory_path = r"D:\data\mouse_hole\everyday\0605\0605_jiancegai\0605_jiancegai11"
process_json_files_in_directory(directory_path)