假如一批数据,分两批分别标注了分割和关键点的json数据,或是分别标注了不同的类别,使用时如果要合并使用,就需要对两个同名的json文件进行合并。
json1:
json2:
合并后json:
脚本内容如下:
import os
import json
import shutildef read_json(in_json_path, json_dict):with open(in_json_path, 'r', encoding='utf-8') as f:json_data = json.load(f)print(json_data['shapes'])json_dict["imagePath"] = json_data["imagePath"]# json_dict["imageData"] = str(base64.b64encode(open(img_path, "rb").read()))# # delete 'b and '# json_dict["imageData"] = json_dict["imageData"][2:-1]json_dict["imageData"] = Nonejson_dict["imageHeight"] = json_data["imageHeight"]json_dict["imageWidth"] = json_data["imageWidth"]json_dict["shapes"].extend(json_data["shapes"])if __name__ == "__main__":output_dir = 'new_jsons'if not os.path.exists(output_dir):os.mkdir(output_dir)json_dict = {"version": "5.1.1","flags": {},"shapes": [],}# 两个json文件存放路径merge_dir_list = ['json-1', 'json-2'] file_name_list = os.listdir(merge_dir_list[0])json_name_list = [i for i in file_name_list if i.endswith('.json')]print(json_name_list)output = "G:/test/merge-json/out"# 遍历要合并的文件for json_name in json_name_list:# "shapes"属性初始化,合并一个文件后,shapes属性初始化json_dict["shapes"] = []for in_dir_name in merge_dir_list:in_json_path = os.path.join(in_dir_name, json_name)# print(in_json_path)read_json(in_json_path, json_dict)# 合并、写入新json文件output_json_path = os.path.join(output_dir, json_dict["imagePath"].split('.')[0] + '.json')# print(output_json_path)with open(output_json_path, 'w') as f:f.write(json.dumps(json_dict))# 文件移动,也可不移动shutil.move('G:/test/merge-json/new_jsons/' + json_name,output)