From b281d52f40cd0dddeef55f628f32382da06dffe3 Mon Sep 17 00:00:00 2001 From: Szabolcs Botond Lorincz Molnar <13637835+lorinczszabolcs@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:45:13 +0100 Subject: [PATCH] Write annotation id and area in COCO output --- src/labelformat/formats/coco.py | 12 +++- .../formats/coco_segmentation_helpers.py | 34 +++++++++++ .../test_instance_segmentation.py | 4 ++ .../object_detection/test_object_detection.py | 6 +- tests/unit/formats/test_coco.py | 61 +++++++++++++++++++ .../formats/test_coco_segmentation_helpers.py | 16 +++++ 6 files changed, 128 insertions(+), 5 deletions(-) diff --git a/src/labelformat/formats/coco.py b/src/labelformat/formats/coco.py index 023f4bb..085b02b 100644 --- a/src/labelformat/formats/coco.py +++ b/src/labelformat/formats/coco.py @@ -185,12 +185,15 @@ def save(self, label_input: ObjectDetectionInput) -> None: data["annotations"] = [] for label in label_input.get_labels(): for obj in label.objects: + bbox = [float(v) for v in obj.box.to_format(BoundingBoxFormat.XYWH)] annotation = { + # COCO annotation IDs start at 1. + "id": len(data["annotations"]) + 1, "image_id": label.image.id, "category_id": obj.category.id, - "bbox": [ - float(v) for v in obj.box.to_format(BoundingBoxFormat.XYWH) - ], + "bbox": bbox, + "area": bbox[2] * bbox[3], + "iscrowd": 0, } if obj.confidence is not None: annotation["score"] = obj.confidence @@ -219,9 +222,12 @@ def save(self, label_input: InstanceSegmentationInput) -> None: isinstance(obj, COCOSingleInstanceSegmentation) and obj.is_crowd ) annotation = { + # COCO annotation IDs start at 1. + "id": len(data["annotations"]) + 1, "image_id": label.image.id, "category_id": obj.category.id, "bbox": bbox, + "area": segmentation_helpers.get_coco_area(segmentation), "iscrowd": int(is_crowd), "segmentation": segmentation, } diff --git a/src/labelformat/formats/coco_segmentation_helpers.py b/src/labelformat/formats/coco_segmentation_helpers.py index 55484f5..3e7ece6 100644 --- a/src/labelformat/formats/coco_segmentation_helpers.py +++ b/src/labelformat/formats/coco_segmentation_helpers.py @@ -1,5 +1,6 @@ from __future__ import annotations +from collections.abc import Sequence from typing import List, TypedDict from labelformat.model.binary_mask_segmentation import ( @@ -89,3 +90,36 @@ def get_coco_segmentation( ) else: raise ValueError(f"Unsupported segmentation type: {type(segmentation)}") + + +def get_coco_area( + segmentation: COCOInstanceSegmentationRLE | COCOInstanceSegmentationMultiPolygon, +) -> float: + """Returns the area in pixels of a COCO segmentation. + + Args: + segmentation: An RLE mask or a list of polygons in COCO format. + + Returns: + The number of foreground pixels for an RLE mask, or the sum of the + polygon areas for a list of polygons. + """ + if isinstance(segmentation, dict): + # Foreground runs are at odd indices. + return float(sum(segmentation["counts"][1::2])) + return float(sum(_polygon_area(polygon) for polygon in segmentation)) + + +def _polygon_area(polygon: Sequence[float]) -> float: + """Returns the area of a polygon with the shoelace formula. + + Args: + polygon: The polygon as a flat list of x and y coordinates. + + Returns: + The area of the polygon. + """ + xs = polygon[0::2] + ys = polygon[1::2] + twice_area = sum(xs[i - 1] * ys[i] - xs[i] * ys[i - 1] for i in range(len(xs))) + return abs(twice_area) / 2 diff --git a/tests/integration/instance_segmentation/test_instance_segmentation.py b/tests/integration/instance_segmentation/test_instance_segmentation.py index ba674a1..5b86052 100644 --- a/tests/integration/instance_segmentation/test_instance_segmentation.py +++ b/tests/integration/instance_segmentation/test_instance_segmentation.py @@ -34,6 +34,7 @@ def test_coco_to_coco(tmp_path: Path) -> None: # - .license # - .flickr_url # - .coco_url + # The output writes new annotation ids and computes the area itself: # - .id # - .area del expected_json["info"] @@ -48,4 +49,7 @@ def test_coco_to_coco(tmp_path: Path) -> None: for annotation in expected_json["annotations"]: del annotation["id"] del annotation["area"] + for annotation in output_json["annotations"]: + del annotation["id"] + del annotation["area"] assert_almost_equal_recursive(output_json, expected_json) diff --git a/tests/integration/object_detection/test_object_detection.py b/tests/integration/object_detection/test_object_detection.py index f619105..bacdbc5 100644 --- a/tests/integration/object_detection/test_object_detection.py +++ b/tests/integration/object_detection/test_object_detection.py @@ -33,9 +33,9 @@ def test_coco_to_coco(tmp_path: Path) -> None: # - licenses # - .supercategory # - .date_captured + # The output writes new annotation ids and computes the area itself: # - .id # - .area - # - .iscrowd del expected_json["info"] del expected_json["licenses"] for category in expected_json["categories"]: @@ -45,7 +45,9 @@ def test_coco_to_coco(tmp_path: Path) -> None: for annotation in expected_json["annotations"]: del annotation["id"] del annotation["area"] - del annotation["iscrowd"] + for annotation in output_json["annotations"]: + del annotation["id"] + del annotation["area"] assert output_json == expected_json diff --git a/tests/unit/formats/test_coco.py b/tests/unit/formats/test_coco.py index ff3d70b..2eb00e2 100644 --- a/tests/unit/formats/test_coco.py +++ b/tests/unit/formats/test_coco.py @@ -10,6 +10,7 @@ COCOObjectDetectionOutput, COCOSingleInstanceSegmentation, ) +from labelformat.formats.labelformat import LabelformatObjectDetectionInput from labelformat.model.binary_mask_segmentation import BinaryMaskSegmentation from labelformat.model.bounding_box import BoundingBox from labelformat.model.category import Category @@ -25,6 +26,8 @@ SimpleInstanceSegmentationInputWithBinaryMask, ) +_FIXTURES_DIR = Path(__file__).parent.parent.parent / "fixtures" + def _create_coco_file(tmp_path: Path, with_score: bool) -> Path: annotations = [ @@ -96,14 +99,20 @@ def test_save(self, tmp_path: Path, with_confidence: bool) -> None: output_json = json.loads(output_file.read_text()) expected_annotations = [ { + "id": 1, "image_id": 0, "category_id": 1, "bbox": [10.0, 20.0, 20.0, 20.0], + "area": 400.0, + "iscrowd": 0, }, { + "id": 2, "image_id": 0, "category_id": 0, "bbox": [50.0, 60.0, 20.0, 20.0], + "area": 400.0, + "iscrowd": 0, }, ] if with_confidence: @@ -111,6 +120,31 @@ def test_save(self, tmp_path: Path, with_confidence: bool) -> None: expected_annotations[1]["score"] = 0.8 assert output_json["annotations"] == expected_annotations + def test_save__area(self, tmp_path: Path) -> None: + output_file = tmp_path / "train.json" + image = Image(id=0, filename="image.jpg", width=100, height=200) + category = Category(id=0, name="cat") + label_input = LabelformatObjectDetectionInput( + categories=[category], + images=[image], + labels=[ + ImageObjectDetection( + image=image, + objects=[ + SingleObjectDetection( + category=category, + box=BoundingBox(xmin=10.0, ymin=20.0, xmax=20.0, ymax=50.0), + ) + ], + ) + ], + ) + + COCOObjectDetectionOutput(output_file=output_file).save(label_input=label_input) + + [annotation] = json.loads(output_file.read_text())["annotations"] + assert annotation["area"] == 300.0 + class TestCOCOInstanceSegmentationInput: @pytest.mark.parametrize("iscrowd", [0, 1]) @@ -203,6 +237,33 @@ def test_save__other_input_is_not_crowd(self, tmp_path: Path) -> None: ] assert [annotation["iscrowd"] for annotation in annotations] == [0, 0] + def test_save__id_and_area(self, tmp_path: Path) -> None: + # The input has a 10x10 polygon and a binary mask with 2 foreground pixels. + output_file = tmp_path / "output.json" + + COCOInstanceSegmentationOutput(output_file=output_file).save( + label_input=SimpleInstanceSegmentationInputWithBinaryMask() + ) + + annotations = json.loads(output_file.read_text())["annotations"] + assert [annotation["id"] for annotation in annotations] == [1, 2] + assert [annotation["area"] for annotation in annotations] == [100.0, 2.0] + + def test_save__area_matches_coco_dataset(self, tmp_path: Path) -> None: + # The fixture holds polygon annotations from the COCO dataset with their areas. + input_file = _FIXTURES_DIR / "instance_segmentation/COCO/instances.json" + output_file = tmp_path / "output.json" + + COCOInstanceSegmentationOutput(output_file=output_file).save( + label_input=COCOInstanceSegmentationInput(input_file=input_file) + ) + + input_annotations = json.loads(input_file.read_text())["annotations"] + output_annotations = json.loads(output_file.read_text())["annotations"] + assert [annotation["area"] for annotation in output_annotations] == [ + pytest.approx(annotation["area"]) for annotation in input_annotations + ] + def _create_coco_instance_segmentation_file( tmp_path: Path, segmentation: object, iscrowd: object diff --git a/tests/unit/formats/test_coco_segmentation_helpers.py b/tests/unit/formats/test_coco_segmentation_helpers.py index 0d4966c..c7b0355 100644 --- a/tests/unit/formats/test_coco_segmentation_helpers.py +++ b/tests/unit/formats/test_coco_segmentation_helpers.py @@ -51,3 +51,19 @@ def test_coco_segmentation_to_multipolygon_rejects_odd_length() -> None: coco_segmentation_helpers.coco_segmentation_to_multipolygon( coco_segmentation=coco_segmentation ) + + +def test_get_coco_area__rle() -> None: + segmentation: COCOInstanceSegmentationRLE = {"counts": [1, 2, 3, 4], "size": [2, 5]} + + assert coco_segmentation_helpers.get_coco_area(segmentation) == 6.0 + + +def test_get_coco_area__polygons() -> None: + # A 2x3 rectangle and a triangle with area 0.5, in opposite vertex orders. + segmentation: COCOInstanceSegmentationMultiPolygon = [ + [0.0, 0.0, 2.0, 0.0, 2.0, 3.0, 0.0, 3.0], + [5.0, 5.0, 5.0, 6.0, 6.0, 5.0], + ] + + assert coco_segmentation_helpers.get_coco_area(segmentation) == 6.5