jsbroks / coco-annotator

:pencil2: Web-based image segmentation tool for object detection, localization, and keypoints
MIT License
2.12k stars 463 forks source link

how can I fix category ID #618

Open YuNie24 opened 1 year ago

YuNie24 commented 1 year ago

I have 5 class to bbox annotate.

But so far, category id is mapped automatically. On the web, I can edit category name, but it seems I can't change category id.

how can i fix category id on each class?

SixK commented 1 year ago

To avoid problems, the best is to create a script to remap your categories id once you have exported annotations.

Here is what a chatgpt tool like say to do (I don't have tested it, but it seem's ok):

To remap categories in a COCO annotation file using a Python script, you can follow these steps:

    Install the required dependencies:
        pip install pycocotools

    Import the necessary libraries:

from pycocotools.coco import COCO
import json

Load the COCO annotation file:

annotation_file = 'path/to/annotation_file.json'
coco = COCO(annotation_file)

Define the mapping of old category IDs to new category IDs:

category_mapping = {
    1: 10,
    2: 20,
    3: 30,
    # add more mappings as needed
}

Create a new category list with remapped IDs:

new_categories = []
for old_cat_id, new_cat_id in category_mapping.items():
    old_cat = coco.loadCats(old_cat_id)[0]
    new_cat = old_cat.copy()
    new_cat['id'] = new_cat_id
    new_categories.append(new_cat)

Update the category list in the COCO annotation file:

coco.dataset['categories'] = new_categories

Update the category IDs in the annotation data:

for annotation in coco.dataset['annotations']:
    old_cat_id = annotation['category_id']
    new_cat_id = category_mapping.get(old_cat_id)
    if new_cat_id:
        annotation['category_id'] = new_cat_id

Save the updated annotation file:

    remapped_annotation_file = 'path/to/remapped_annotation_file.json'
    with open(remapped_annotation_file, 'w') as f:
        json.dump(coco.dataset, f)

That's it! The resulting COCO annotation file with remapped categories will be saved as remapped_annotation_file.json. Make sure to replace 'path/to/annotation_file.json' and 'path/to/remapped_annotation_file.json' with the actual file paths.

Please note that this script assumes that the COCO annotation file follows the standard COCO format.