1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| import os import json
def convert_labelme_to_yolo(json_file, output_folder, class_dict): with open(json_file, 'r') as f: data = json.load(f)
img_width = data['imageWidth'] img_height = data['imageHeight']
img_name = os.path.splitext(os.path.basename(json_file))[0]
txt_filename = os.path.join(output_folder, img_name + '.txt') with open(txt_filename, 'w') as f: for shape in data['shapes']: if shape['shape_type'] != 'rectangle': continue
label = shape['label'] class_id = class_dict[label]
points = shape['points'] xmin, ymin = points[0] xmax, ymax = points[1]
x_center = (xmin + xmax) / 2.0 / img_width y_center = (ymin + ymax) / 2.0 / img_height width = (xmax - xmin) / img_width height = (ymax - ymin) / img_height
line = f"{class_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\n" f.write(line)
def main():
class_dict = { 'Short sleeve top': 1, 'Long sleeve top': 2, 'Short sleeve outwear': 3, 'Long sleeve outwear': 4, 'Vest': 5, 'Sling': 6, 'Shorts': 7, 'Trousers': 8, 'Skirt': 9, 'Short sleeve dress': 10, 'Long sleeve dress': 11, 'Vest dress': 12, 'Sling dress': 13, }
input_folder = 'train\\annos' output_folder = 'train\\lables'
for filename in os.listdir(input_folder): if filename.endswith('.json'): json_file = os.path.join(input_folder, filename) convert_labelme_to_yolo(json_file, output_folder, class_dict)
if __name__ == "__main__": main()
|