Skip to content

Conversation

@horatiualmasan
Copy link
Contributor

Add support for the CVAT label format import and export.
Added Unit tests

@horatiualmasan horatiualmasan marked this pull request as ready for review March 7, 2025 07:34
Copy link
Contributor

@MalteEbner MalteEbner left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While I think that the code works, I don't that that the way that the XML is parsed is the best:

  • It is hard to find out which CVAT structure is assumed and how it is check. The required attributes are split among many places
  • The validation and error message handling make up a lot of the code. However, I think that they are sometimes inconsistent and will miss many cases. Just an example: What if self._data.findall("image") does not find a list of images, but a single image? Then the iteration over it will fail and there is no error message for it. What if you want to cast an attribute to int that is not castable?

I think the best solution is to use pydantic-xml to

  • Define the expected cvat xml structure nicely as dataclasses, making the expected structure and attributes super clear and defined at once place.
  • Clearly separate the parsing (output is the pydantic dataclasses) from the transformation to the labelformat classes and don't mix it.
  • Let pydantic handle all the parsing, validation and error messages.

Below a self-contained example for doing all the input parsing, validation, transformation and error handling. No helper methods are needed at all. The output can be added in a similar way.

from argparse import ArgumentParser
from pathlib import Path
from typing import Iterable, Dict, List

from pydantic_xml import BaseXmlModel, attr, element

# --- Pydantic XML models ---

class CVATLabel(BaseXmlModel, tag="label"):
    name: str = element()

class CVATTask(BaseXmlModel, tag="task"):
    labels: list[CVATLabel] = element(tag="label")

class CVATJob(BaseXmlModel, tag="job"):
    labels: list[CVATLabel] = element(tag="label")

class CVATProject(BaseXmlModel, tag="project"):
    labels: list[CVATLabel] = element(tag="label")

class CVATMeta(BaseXmlModel, tag="meta"):
    task: CVATTask | None = element(default=None)
    job: CVATJob | None = element(default=None)
    project: CVATProject | None = element(default=None)

class CVATBox(BaseXmlModel, tag="box"):
    label: str = attr()
    xtl: float = attr()
    ytl: float = attr()
    xbr: float = attr()
    ybr: float = attr()

class CVATImage(BaseXmlModel, tag="image"):
    id: int = attr()
    name: str = attr()  # Filename
    width: int = attr()
    height: int = attr()
    boxes: list[CVATBox] = element(tag="box", default=[])

class CVATAnnotations(BaseXmlModel, tag="annotations"):
    meta: CVATMeta = element()
    images: list[CVATImage] = element(tag="image", default=[])

# --- Input classes ---

class _CVATBaseInput:
    @staticmethod
    def add_cli_arguments(parser: ArgumentParser) -> None:
        parser.add_argument(
            "--input-file",
            type=Path,
            required=True,
            help="Path to input CVAT XML file",
        )

    def __init__(self, input_file: Path) -> None:
        with input_file.open("r", encoding="utf-8") as file:
            xml_content = file.read()
        self._data = CVATAnnotations.from_xml(xml_content)

    def get_categories(self) -> Iterable["Category"]:
        meta = self._data.meta
        labels: List[CVATLabel] | None = None
        if meta.task is not None and meta.task.labels:
            labels = meta.task.labels
        elif meta.job is not None and meta.job.labels:
            labels = meta.job.labels
        elif meta.project is not None and meta.project.labels:
            labels = meta.project.labels
        if labels is None:
            raise ValueError(
                "Could not find labels in meta/task, meta/job, or meta/project"
            )
        for idx, label in enumerate(labels, start=1):
            yield Category(id=idx, name=label.name)

    def get_images(self) -> Iterable["Image"]:
        for img in self._data.images:
            yield Image(
                id=img.id,
                filename=img.name,
                width=img.width,
                height=img.height,
            )

class CVATObjectDetectionInput(_CVATBaseInput, ObjectDetectionInput):
    def get_labels(self) -> Iterable["ImageObjectDetection"]:
        category_by_name: Dict[str, Category] = {
            cat.name: cat for cat in self.get_categories()
        }
        for img in self._data.images:
            objects = []
            for box in img.boxes:
                cat = category_by_name.get(box.label)
                if cat is None:
                    continue  # or handle error as needed
                objects.append(
                    SingleObjectDetection(
                        category=cat,
                        box=BoundingBox.from_format(
                            bbox=[box.xtl, box.ytl, box.xbr, box.ybr],
                            format=BoundingBoxFormat.XYXY,
                        ),
                    )
                )
            yield ImageObjectDetection(
                image=Image(id=img.id, filename=img.name, width=img.width, height=img.height),
                objects=objects,
            )

Copy link
Contributor

@MalteEbner MalteEbner left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, well done!

Copy link
Contributor

@MalteEbner MalteEbner left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, but I just stumbled upon a problem in the code I suggested.

Copy link
Contributor

@MalteEbner MalteEbner left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, well done!

@horatiualmasan horatiualmasan merged commit a020416 into main Mar 12, 2025
2 checks passed
@horatiualmasan horatiualmasan deleted the horatiu-lig-6192-add-support-for-cvat-annotation-format-for-labelformat branch March 12, 2025 14:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants