comparison json2yolosegment.py @ 0:252fd085940d draft

planemo upload for repository https://github.com/bgruening/galaxytools/tree/master/tools commit 67e0e1d123bcfffb10bab8cc04ae67259caec557
author bgruening
date Fri, 13 Jun 2025 11:23:35 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:252fd085940d
1 import argparse
2 import json
3 import os
4
5
6 def convert_json_to_yolo(input_dir, save_dir, class_names_file):
7
8 with open(class_names_file, 'r') as f:
9 class_names = [line.strip() for line in f.readlines()]
10
11 class_to_index = {class_name: i for i, class_name in enumerate(class_names)}
12
13 for filename in os.listdir(input_dir):
14 json_filepath = os.path.join(input_dir, filename)
15
16 with open(json_filepath, 'r') as f:
17 data = json.load(f)
18
19 image_width = data.get('imageWidth')
20 image_height = data.get('imageHeight')
21 if image_width is None or image_height is None:
22 print(f"Skipping {filename}: missing image dimensions.")
23 return
24
25 annotations = data.get('shapes', [])
26
27 base, _ = os.path.splitext(filename)
28 output_file = f"{base}.txt"
29 output_filepath = os.path.join(save_dir, output_file)
30
31 with open(output_filepath, 'w') as f:
32 for annotation in annotations:
33 label = annotation.get('label')
34 class_index = class_to_index[label]
35
36 points = annotation.get('points', [])
37
38 if not points:
39 print(f"No points found for annotation '{label}', skipping.")
40 continue
41
42 x = [point[0] / (image_width - 1) for point in points]
43 y = [point[1] / (image_height - 1) for point in points]
44
45 segmentation_points = ['{} {}'.format(x[i], y[i]) for i in range(len(x))]
46 segmentation_points_string = ' '.join(segmentation_points)
47 line = '{} {}\n'.format(class_index, segmentation_points_string)
48 f.write(line)
49
50 print(f"Converted annotations saved to: {output_filepath}")
51
52
53 def main():
54 parser = argparse.ArgumentParser(description="Convert JSON annotations to YOLO segment format.")
55 parser.add_argument('-i', '--input_dir', type=str, help='Full path of the folder containing AnyLabeling JSON files.')
56 parser.add_argument('-o', '--save_dir', type=str, help='Path to the directory to save converted YOLO files.')
57 parser.add_argument('-c', '--class_names_file', type=str, help='Path to the text file containing class names, one per line.')
58 args = parser.parse_args()
59
60 convert_json_to_yolo(args.input_dir, args.save_dir, args.class_names_file)
61
62
63 if __name__ == "__main__":
64 main()