从COCO数据集的keypoints的json文件中,读取特定image_id的annotations内容
比如,我需要查看的image_id为50713,我需要将该image_id所在的annotations的内容都打印出来,代码如下:
import json
input_file_path = r'W:\yolo_pose\annotations_trainval2017\annotations\person_keypoints_train2017.json'
output_file_path = r'W:\yolo_pose\image_id50713.json'
# 打开并加载JSON数据
with open(input_file_path, 'r') as f:
data = json.load(f)
# 获取annotations列表
annotations = data.get('annotations', [])
# 要查找的特定image_id
target_image_id = 50713
# 检查annotations列表是否为空
if annotations:
# 遍历annotations列表
for annotation in annotations:
# 检查annotation的image_id是否与目标image_id匹配
if annotation.get('image_id') == target_image_id:
# 将匹配的annotation的内容写入新的JSON文件
with open(output_file_path, 'w') as out_f:
json.dump(annotation, out_f, ensure_ascii=False, indent=4)
print(f"特定image_id为{target_image_id}的annotation内容已保存到:{output_file_path}")
break # 找到匹配项后退出循环
else:
print("没有找到annotations数据。")