import os
import json
def load_json(filenamejson):
with open(filenamejson) as f:
root_data = json.load(f)
return root_data
def recon_coco_json(file_path):
files = next(os.walk(file_path))[2]
filenamejson = file_path + str(files[0])
# 读取文件
root_data = load_json(filenamejson)
root_images_len = len(root_data['images'])
root_annotations_len = len(root_data['annotations'])
ser_num1 = 1
# 照片id从1开始
ser_num2 = 10000
#标注id从10000开始
for i in range(root_images_len):
for j in range(root_annotations_len):
if(root_data['annotations'][j]['image_id'] == root_data['images'][i]['id']):
root_data['annotations'][j]['image_id'] = int(ser_num1)
root_data['images'][i]['id'] = int(ser_num1)
ser_num1 = ser_num1 + 1
for j in range(root_annotations_len):
root_data['annotations'][j]['id'] = int(ser_num2)
ser_num2 = ser_num2 + 1
json_str = json.dumps(root_data)
with open('recon.json', 'w') as json_file:
json_file.write(json_str)
print("Success!")
file_path = "C:\\Users\\DELL\\Desktop\\co\\" #重新编号的路径
if __name__ == "__main__":
recon_coco_json(file_path)
COCO文件的id从1开始排序
最新推荐文章于 2023-10-11 11:19:22 发布