这是从图像目录生成图像详细信息并将其写入现有 COCO JSON 文件的方法:
from PIL import Image
def add_images_to_coco(image_dir, coco_filename):
image_filenames = list(Path(image_dir).glob('*.jpg'))
images = []
for i, image_filename in enumerate(image_filenames):
im = Image.open(image_filename)
width, height = im.size
image_details = {
"id": id + 1,
"height": height,
"width": width,
"file_name": str(image_filename.resolve()),
}
images.append(image_details)
# This will overwrite the image tags in the COCO JSON file
with open(coco_filename) as f:
data = json.load(f)
coco['images'] = images
with open(coco_filename, 'w') as coco_file:
json.dump(data, coco_file, indent = 4)
如果您还没有类别,则需要使用您的类别创建一个基线 COCO JSON 文件。它应该看起来像这样:
{
"images": [ ],
"annotations": [ ],
"categories": [
{
"id": 1,
"name": "Car",
"supercategory": "Car"
},
{
"id": 2,
"name": "Person",
"supercategory": "Person"
}
]
}