util.py 2.0 KB
Newer Older
M
Maxim Zhiltsov 已提交
1 2 3 4 5
# Copyright (C) 2022 CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT

import textwrap
6
from pathlib import Path
M
Maxim Zhiltsov 已提交
7 8 9 10 11 12 13 14 15 16
from typing import Tuple

from cvat_sdk.core.helpers import TqdmProgressReporter
from tqdm import tqdm


def make_pbar(file, **kwargs):
    return TqdmProgressReporter(tqdm(file=file, mininterval=0, **kwargs))


17
def generate_coco_json(filename: Path, img_info: Tuple[Path, int, int]):
M
Maxim Zhiltsov 已提交
18 19 20
    image_filename, image_width, image_height = img_info

    content = generate_coco_anno(
21
        image_filename.name,
M
Maxim Zhiltsov 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35
        image_width=image_width,
        image_height=image_height,
    )
    with open(filename, "w") as coco:
        coco.write(content)


def generate_coco_anno(image_path: str, image_width: int, image_height: int) -> str:
    return (
        textwrap.dedent(
            """
    {
        "categories": [
            {
36 37 38
                "id": 1,
                "name": "car",
                "supercategory": ""
M
Maxim Zhiltsov 已提交
39 40
            },
            {
41 42 43
                "id": 2,
                "name": "person",
                "supercategory": ""
M
Maxim Zhiltsov 已提交
44 45 46 47
            }
        ],
        "images": [
            {
48 49 50 51 52 53 54 55
                "coco_url": "",
                "date_captured": "",
                "flickr_url": "",
                "license": 0,
                "id": 0,
                "file_name": "%(image_path)s",
                "height": %(image_height)d,
                "width": %(image_width)d
M
Maxim Zhiltsov 已提交
56 57 58 59
            }
        ],
        "annotations": [
            {
60 61 62 63 64 65 66 67 68 69 70 71 72 73
                "category_id": 1,
                "id": 1,
                "image_id": 0,
                "iscrowd": 0,
                "segmentation": [
                    []
                ],
                "area": 17702.0,
                "bbox": [
                    574.0,
                    407.0,
                    167.0,
                    106.0
                ]
M
Maxim Zhiltsov 已提交
74 75 76 77 78 79 80 81 82 83 84
            }
        ]
    }
    """
        )
        % {
            "image_path": image_path,
            "image_height": image_height,
            "image_width": image_width,
        }
    )