注意,这只是把单一123.jpg.json文件转化为123.txt
并没有把整体的json文件转换
import json
# 读取JSON文件
json_file_path = r'G:\bsh\dataset\flame_test_dataset\train\annotations\259.jpg.json'
with open(json_file_path, 'r') as json_file:
data = json.load(json_file)
# 提取相关信息
image_width = data["width"]
image_height = data["height"]
objects = data["step_1"]["result"]
# 创建YOLO格式文本
yolo_txt = ""
for obj in objects:
x = obj["x"]
y = obj["y"]
width = obj["width"]
height = obj["height"]
class_id = obj["attribute"]
# 将坐标转换为YOLO格式(中心坐标/宽度/高度)
x_center = (x+0.5*width) / image_width
y_center = (y+0.5*height) / image_height
width = width / image_width
height = height / image_height
yolo_txt += f"{class_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\n"
# 将YOLO格式文本保存到文件
output_txt_path = r'G:\bsh\dataset\flame_test_dataset\train\annotations\259.txt'
with open(output_txt_path, 'w') as output_file:
output_file.write(yolo_txt)
print(f"已将JSON数据转换为YOLO格式并保存到 {output_txt_path}。")