SAHI

Published by onesixx on

Convert any dataset to COCO object detection format with SAHIFatih Cagatay Akyon

kitty-tiny to Coco

# https://www.immersivelimit.com/tutorials/create-coco-annotations-from-scratch
# https://github.com/obss/sahi/blob/main/docs/coco.md
# from distutils.log import info
# import inspect

# ****** Import required classes
from sahi.utils.coco import Coco, CocoCategory, CocoImage, CocoAnnotation
from sahi.utils.file import save_json

import mmcv
import os
from PIL import Image

path_root = './kitti_tiny/'
path_img  = os.path.join(path_root, 'training/image_2')
path_anno = os.path.join(path_root, 'training/label_2')

fullNm_trainSet = os.path.join(path_root,'train.txt')

# ****** Init Coco object
coco = Coco()

# ****** Add Category (id from 0)
CLASSES = ('Car', 'Truck', 'Pedestrian', 'Cyclist')

for i, cls in enumerate(CLASSES):
    coco.add_category(
        CocoCategory(id=i, name=cls)
    )

# ****** Add Image
image_list = mmcv.list_from_file(fullNm_trainSet)
cate2anno = {c:i for i, c in enumerate(CLASSES)}

for id, image_id in enumerate(image_list):
    #image_id = image_list[0]

    filenNm = f'{image_id}.jpeg' 
    img_fullNm = os.path.join(path_img, filenNm)
    width, height = Image.open(img_fullNm).size
    coco_image = CocoImage(
        height=height,
        width=width, 
        id = id,
        file_name = filenNm
    )

    # ****** Add Annotation 
    anno4Img = mmcv.list_from_file(os.path.join(path_anno, image_id+'.txt'))
    # annoList = [line.strip().split(' ') for line in anno4Img]
    # bbox_labels = [row[0] for row in annoList]
    # bboxes = [ [float(info) for info in row[4:8]] for row in annoList]

    for i, line in enumerate(anno4Img):
        # line = lines[1]
        row = line.strip().split(' ')
        bbox_label = row[0]
        if bbox_label in cate2anno:
            cateId = cate2anno[bbox_label]
            #cateNm = CLASSES[cateId]
            # [x_min, y_min, width, height],
            pnt = [float(info) for info in row[4:8]] 
            bboxes = [pnt[0], pnt[1], pnt[2]-pnt[0], pnt[3]-pnt[1]]

            coco_image.add_annotation(
                CocoAnnotation( 
                    image_id     = id,
                    bbox         = bboxes, 
                    segmentation = [],   
                    category_id  = cateId
                )
            )
        else:
            pass
            # "segmentation" =[],
            # "attribute"
            # "id" auto 
    # ****** add coco image to coco Object
    coco.add_image(coco_image)

coco_json = coco.json
coco_json["licenses"] = [dict()]
coco_json["info"] = [dict(items="x", dictionary ='x')]

fullNm_result = os.path.join(path_root,'anno_cc.json')
save_json(data=coco_json, save_path=fullNm_result)



Categories: vision

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x