import json
import os
def json_to_txt(json_path, txt_path):
with open(json_path, 'r') as json_file:
data = json.load(json_file)
with open(txt_path, 'w') as txt_file:
for shape in data['shapes']:
if shape['shape_type'] == 'polygon':
points = shape['points']
label = shape['label']
txt_file.write(f"{label} {' '.join([f'{x},{y}' for x, y in points])}\n")
def batch_convert_json_to_txt(json_folder, txt_folder):
os.makedirs(txt_folder, exist_ok=True)
for json_file in os.listdir(json_folder):
if json_file.endswith('.json'):
json_path = os.path.join(json_folder, json_file)
txt_file = os.path.splitext(json_file)[0] + '.txt'
txt_path = os.path.join(txt_folder, txt_file)
json_to_txt(json_path, txt_path)
if __name__ == "__main__":
json_folder = r'/path/to/json/folder'
txt_folder = r'/path/to/txt/folder'
batch_convert_json_to_txt(json_folder, txt_folder)
请注意替换/path/to/json/folder
和/path/to/txt/folder
为你实际的文件夹路径。
第一个为你json文件存放的文件夹路径,第二个为转换为txt路径后存放的文件夹路径,路径建议用绝对路径