import json
import os
def convert(size, box):
dw = 1. / size[0]
dh = 1. / size[1]
x = (box[0] + box[2]) / 2.0
y = (box[1] + box[3]) / 2.0
w = box[2] - box[0]
h = box[3] - box[1]
x = x * dw
w = w * dw
y = y * dh
h = h * dh
return (x, y, w, h)
def decode_json(json_path, output_dir):
with open(json_path, 'r') as f:
data = json.load(f)
base_name = os.path.splitext(os.path.basename(data['imagePath']))[0]
txt_path = os.path.join(output_dir, base_name + '.txt')
with open(txt_path, 'w') as txt_file:
for shape in data['shapes']:
if shape['shape_type'] == 'rectangle':
label = shape['label']
points = shape['points']
x1, y1 = points[0]
x2, y2 = points[1] # Assuming the points are diagonal
bb = convert((data['imageWidth'], data['imageHeight']), [x1, y1, x2, y2])
txt_file.write(f"{label} {' '.join(map(str, bb))}\n")
# # ...之前的代码...
#
# def decode_json(json_path, output_dir):
# with open(json_path, 'r') as f:
# data = json.load(f)
#
# base_name = os.path.splitext(os.path.basename(data['imagePath']))[0]
# txt_path = os.path.join(output_dir, base_name + '.txt')
# with open(txt_path, 'w') as txt_file:
# for shape in data['shapes']:
# if shape['shape_type'] == 'rectangle':
# label = shape['label']
# points = shape['points']
#
# # 只使用第一个和第三个点定义矩形(假设点是按顺序排列的)
# x1, y1 = points[0]
# x3, y3 = points[2]
#
# # 通过提取左上角和右下角的点来转换坐标并写入文件
# try:
# bb = convert((data['imageWidth'], data['imageHeight']), [x1, y1, x3, y3])
# txt_file.write(f"{label} {' '.join(map(str, bb))}\n")
# except ValueError as e:
# print(f"Error converting box with label {label}: {e}")
# continue
#
# # # ...之后的代码...
if __name__ == "__main__":
json_folder_path = r'D:\Pycharm-Projects\ultralytics-main\json' # JSON 文件所在的文件夹路径
output_dir = r'D:\Pycharm-Projects\ultralytics-main\yolo_labels' # 转换后的 YOLO 格式文本文件存放的文件夹路径,建议与JSON文件夹分开
json_files = [file for file in os.listdir(json_folder_path) if file.endswith('.json')]
for json_file in json_files:
json_path = os.path.join(json_folder_path, json_file)
decode_json(json_path, output_dir)
将 json_folder_path 替换为你存放 JSON 文件的实际文件夹路径,将 output_dir 替换为你想要保存转换后的 YOLO 格式文本文件的文件夹路径