Add support for CVAT annotation format#29
Merged
horatiualmasan merged 24 commits intomainfrom Mar 12, 2025
Merged
Conversation
MalteEbner
reviewed
Mar 7, 2025
Contributor
There was a problem hiding this comment.
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 tointthat 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,
)
Merged
… horatiu-lig-6192-add-support-for-cvat-annotation-format-for-labelformat
MalteEbner
reviewed
Mar 11, 2025
Contributor
MalteEbner
left a comment
There was a problem hiding this comment.
Looks good, well done!
MalteEbner
reviewed
Mar 12, 2025
Contributor
MalteEbner
left a comment
There was a problem hiding this comment.
Sorry, but I just stumbled upon a problem in the code I suggested.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Add support for the CVAT label format import and export.
Added Unit tests