JSON 注释错误 "string indices must be integers"

JSON annotations error "string indices must be integers"

写了一个函数来解析 COCO JSON。如何解决错误? 这里的示例 file_name 是:hard_hat_workers2819_png.rf.6870e9b0e6f5cd67d581d9d6185124e6.jpg 由于数据集很大,因此无法更改文件的名称。我该怎么办?

[在此处输入图片描述][1]

def get_board_dicts(imgdir):
    json_file = imgdir+"/_annotations.coco.json" #Fetch the json file
    with open(json_file) as f:
        dataset_dicts = json.load(f) #loads(jsonStr)
    for i in dataset_dicts:
        filename = i['file_name'] 
        i['file_name'] = imgdir+"/"+filename 
        for j in i["annotations"]:
            j["bbox_mode"] = BoxMode.XYWH_ABS #Setting the required Box Mode
            j["category_id"] = int(j["category_id"])
    return dataset_dicts 


---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)
<ipython-input-21-3c960c9b4cee> in <module>()
      1 #Visualizing the Train Dataset
----> 2 dataset_dicts = get_board_dicts("HardHat_COCO/train")
      3 #Randomly choosing 3 images from the Set
      4 for d in random.sample(dataset_dicts, 3):
      5     img = cv2.imread(d["file_name"])

<ipython-input-20-a32bcb391fe9> in get_board_dicts(imgdir)
      7         dataset_dicts = json.load(f) #loads(jsonStr)
      8     for i in dataset_dicts:
----> 9         filename = i['file_name']
     10         i['file_name'] = imgdir+"/"+filename
     11         for j in i["annotations"]:

TypeError: string indices must be integers 


  #samples from COCO JSON file:
"images": [
        {
            "id": 0,
            "license": 1,
            "file_name": "hard_hat_workers2819_png.rf.6870e9b0e6f5cd67d581d9d6185124e6.jpg",
            "height": 416,
            "width": 416,
            "date_captured": "2021-08-31T14:27:07+00:00"
        },
        {
            "id": 1,
            "license": 1,
            "file_name": "hard_hat_workers239_png.rf.68144af0d963cc745832ccbf69cd93ec.jpg",
            "height": 416,
            "width": 416,
            "date_captured": "2021-08-31T14:27:07+00:00"
        },

很难说,但你可能是这个意思:

for i in dataset_dicts['images']:
    filename = i['file_name']
    ...