python生成分类问题LIST的json文件
import os
import json
import glob
def get_annotation_dict(input_folder_path):
label_dict = {}
image_set = []
annonation_set = []
# 主目录
father_file_list = os.listdir(input_folder_path)
# class 目录
count = 0
for class_file in father_file_list:
full_class_file = os.path.join(input_folder_path, class_file)
class_file_list = os.listdir(full_class_file)
# 相对路径的路径
class_file_com = 'train_val2019/'+class_file
# print(len([x for x in os.listdir(os.path.dirname(class_file_list)) if os.path.isfile(x)]),'当前文件数')
for image_name in class_file_list:
image_file_id ={}
annonation_id_catgoly = {}
image_file_id["filename"] = os.path.join(class_file_com, image_name)
image_file_id["id"] = count
annonation_id_catgoly['id'] = count
annonation_id_catgoly['category_id'] = class_file
image_set.append(image_file_id)
annonation_set.append(annonation_id_catgoly)
count = count +1
label_dict['images'] = image_set
print(image_set,'image')
label_dict['annotation'] = annonation_set
print(annonation_set,'ann')
return label_dict
def save_json(label_dict, json_path):
with open(json_path, 'w') as json_path:
json.dump(label_dict, json_path)
print('label json file has been generated successfully')
if __name__ == '__main__':
input_folder_file = '/home/chensheng/code/DL/STEGO/train_val2019'
label_dict = {}
label_dict = get_annotation_dict(input_folder_file)
json_path = '/home/chensheng/code/DL/STEGO/train2019.json'
save_json(label_dict, json_path)