From 4cdc2851749a8e5d81a0929271adbe956eee96b0 Mon Sep 17 00:00:00 2001 From: Szabolcs Botond Lorincz Molnar <13637835+lorinczszabolcs@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:19:21 +0100 Subject: [PATCH] Keep the crowd flag of COCO and YouTube-VIS instance segmentations --- src/labelformat/formats/coco.py | 16 ++-- .../formats/coco_segmentation_helpers.py | 5 +- src/labelformat/formats/youtubevis.py | 8 +- .../model/instance_segmentation.py | 1 + .../model/instance_segmentation_track.py | 1 + .../integration/test_maskpair_integration.py | 2 +- tests/unit/formats/test_coco.py | 90 ++++++++++++++++++- tests/unit/formats/test_youtubevis.py | 20 +++++ 8 files changed, 126 insertions(+), 17 deletions(-) diff --git a/src/labelformat/formats/coco.py b/src/labelformat/formats/coco.py index fbde286..19cbd1e 100644 --- a/src/labelformat/formats/coco.py +++ b/src/labelformat/formats/coco.py @@ -3,7 +3,7 @@ import json from argparse import ArgumentParser from pathlib import Path -from typing import Dict, Iterable, List +from typing import Dict, Iterable, List, cast import fsspec @@ -118,10 +118,13 @@ def get_labels(self) -> Iterable[ImageInstanceSegmentation]: if "segmentation" not in ann: raise ParseError(f"Segmentation missing for image id {image_id}") segmentation: MultiPolygon | BinaryMaskSegmentation - if ann["iscrowd"] == 1: + if isinstance(ann["segmentation"], dict): + segmentation_rle = cast( + COCOInstanceSegmentationRLE, ann["segmentation"] + ) segmentation = ( segmentation_helpers.coco_segmentation_to_binary_mask_rle( - segmentation=ann["segmentation"], bbox=ann["bbox"] + segmentation=segmentation_rle, bbox=ann["bbox"] ) ) else: @@ -134,6 +137,7 @@ def get_labels(self) -> Iterable[ImageInstanceSegmentation]: SingleInstanceSegmentation( category=category_id_to_category[ann["category_id"]], segmentation=segmentation, + is_crowd=ann["iscrowd"] == 1, ) ) yield ImageInstanceSegmentation( @@ -194,14 +198,14 @@ def save(self, label_input: InstanceSegmentationInput) -> None: data["annotations"] = [] for label in label_input.get_labels(): for obj in label.objects: - segmentation, bbox, is_crowd = ( - segmentation_helpers.get_coco_segmentation(obj.segmentation) + segmentation, bbox = segmentation_helpers.get_coco_segmentation( + obj.segmentation ) annotation = { "image_id": label.image.id, "category_id": obj.category.id, "bbox": bbox, - "iscrowd": is_crowd, + "iscrowd": int(obj.is_crowd), "segmentation": segmentation, } data["annotations"].append(annotation) diff --git a/src/labelformat/formats/coco_segmentation_helpers.py b/src/labelformat/formats/coco_segmentation_helpers.py index c5d0235..55484f5 100644 --- a/src/labelformat/formats/coco_segmentation_helpers.py +++ b/src/labelformat/formats/coco_segmentation_helpers.py @@ -75,20 +75,17 @@ def get_coco_segmentation( ) -> tuple[ COCOInstanceSegmentationRLE | COCOInstanceSegmentationMultiPolygon, List[float], - bool, ]: - """Returns coco segmentation, bbox in xywh format and iscrowd flag for the given segmentation.""" + """Returns coco segmentation and bbox in xywh format for the given segmentation.""" if isinstance(segmentation, BinaryMaskSegmentation): return ( _binary_mask_rle_to_coco_segmentation(segmentation), segmentation.bounding_box.to_format(BoundingBoxFormat.XYWH), - True, ) elif isinstance(segmentation, MultiPolygon): return ( _multipolygon_to_coco_segmentation(segmentation), segmentation.bounding_box().to_format(BoundingBoxFormat.XYWH), - False, ) else: raise ValueError(f"Unsupported segmentation type: {type(segmentation)}") diff --git a/src/labelformat/formats/youtubevis.py b/src/labelformat/formats/youtubevis.py index fc751ec..498fdb3 100644 --- a/src/labelformat/formats/youtubevis.py +++ b/src/labelformat/formats/youtubevis.py @@ -121,6 +121,7 @@ def get_labels(self) -> Iterable[VideoInstanceSegmentationTrack]: category=category_id_to_category[track["category_id"]], segmentations=segmentations, object_track_id=track.get("id"), + is_crowd=track.get("iscrowd", 0) == 1, ) ) yield VideoInstanceSegmentationTrack( @@ -201,16 +202,13 @@ def _get_output_annotations_dict( | None ] = [] areas_list: List[int | None] = [] - iscrowd = 0 for seg in obj.segmentations: if seg is None: bboxes_list.append(None) segmentations_list.append(None) areas_list.append(None) continue - segmentation, bbox, iscrowd = ( - segmentation_helpers.get_coco_segmentation(seg) - ) + segmentation, bbox = segmentation_helpers.get_coco_segmentation(seg) if isinstance(segmentation, dict): # RLE segmentation area = sum( segmentation["counts"][1::2] @@ -234,7 +232,7 @@ def _get_output_annotations_dict( "bboxes": bboxes_list, "segmentations": segmentations_list, "areas": areas_list, - "iscrowd": iscrowd, + "iscrowd": int(obj.is_crowd), "height": height, "width": width, "length": length, diff --git a/src/labelformat/model/instance_segmentation.py b/src/labelformat/model/instance_segmentation.py index 39a5946..2c8692e 100644 --- a/src/labelformat/model/instance_segmentation.py +++ b/src/labelformat/model/instance_segmentation.py @@ -15,6 +15,7 @@ class SingleInstanceSegmentation: category: Category segmentation: MultiPolygon | BinaryMaskSegmentation + is_crowd: bool = False @dataclass(frozen=True) diff --git a/src/labelformat/model/instance_segmentation_track.py b/src/labelformat/model/instance_segmentation_track.py index 3493499..d8d4b00 100644 --- a/src/labelformat/model/instance_segmentation_track.py +++ b/src/labelformat/model/instance_segmentation_track.py @@ -16,6 +16,7 @@ class SingleInstanceSegmentationTrack: category: Category segmentations: list[MultiPolygon | BinaryMaskSegmentation | None] object_track_id: int | None = None + is_crowd: bool = False @dataclass(frozen=True) diff --git a/tests/integration/test_maskpair_integration.py b/tests/integration/test_maskpair_integration.py index dce4494..65961dd 100644 --- a/tests/integration/test_maskpair_integration.py +++ b/tests/integration/test_maskpair_integration.py @@ -165,7 +165,7 @@ def test_rle_segmentation_format(self, tmp_path: Path) -> None: # Verify that annotations use RLE format for ann in coco_data["annotations"]: - assert ann["iscrowd"] == 1 # RLE format + assert ann["iscrowd"] == 0 # Each mask is one object. assert "counts" in ann["segmentation"] assert "size" in ann["segmentation"] diff --git a/tests/unit/formats/test_coco.py b/tests/unit/formats/test_coco.py index c0805c6..c3fd5c5 100644 --- a/tests/unit/formats/test_coco.py +++ b/tests/unit/formats/test_coco.py @@ -3,10 +3,17 @@ import pytest -from labelformat.formats.coco import COCOObjectDetectionInput, COCOObjectDetectionOutput +from labelformat.formats.coco import ( + COCOInstanceSegmentationInput, + COCOInstanceSegmentationOutput, + COCOObjectDetectionInput, + COCOObjectDetectionOutput, +) +from labelformat.model.binary_mask_segmentation import BinaryMaskSegmentation from labelformat.model.bounding_box import BoundingBox from labelformat.model.category import Category from labelformat.model.image import Image +from labelformat.model.multipolygon import MultiPolygon from labelformat.model.object_detection import ( ImageObjectDetection, SingleObjectDetection, @@ -99,3 +106,84 @@ def test_save(self, tmp_path: Path, with_confidence: bool) -> None: expected_annotations[0]["score"] = 0.4 expected_annotations[1]["score"] = 0.8 assert output_json["annotations"] == expected_annotations + + +class TestCOCOInstanceSegmentationInput: + @pytest.mark.parametrize("iscrowd", [0, 1]) + def test_get_labels__rle(self, tmp_path: Path, iscrowd: int) -> None: + input_file = _create_coco_instance_segmentation_file( + tmp_path=tmp_path, + segmentation={"counts": [2, 4], "size": [2, 3]}, + iscrowd=iscrowd, + ) + + [label] = COCOInstanceSegmentationInput(input_file=input_file).get_labels() + + [obj] = label.objects + assert isinstance(obj.segmentation, BinaryMaskSegmentation) + assert obj.segmentation.get_rle() == [1, 2, 1, 2] + assert obj.is_crowd == (iscrowd == 1) + + @pytest.mark.parametrize("iscrowd", [0, 1]) + def test_get_labels__polygon(self, tmp_path: Path, iscrowd: int) -> None: + input_file = _create_coco_instance_segmentation_file( + tmp_path=tmp_path, + segmentation=[[1.0, 0.0, 3.0, 0.0, 3.0, 2.0, 1.0, 2.0]], + iscrowd=iscrowd, + ) + + [label] = COCOInstanceSegmentationInput(input_file=input_file).get_labels() + + [obj] = label.objects + assert isinstance(obj.segmentation, MultiPolygon) + assert obj.segmentation.polygons == [ + [(1.0, 0.0), (3.0, 0.0), (3.0, 2.0), (1.0, 2.0)] + ] + assert obj.is_crowd == (iscrowd == 1) + + +class TestCOCOInstanceSegmentationOutput: + @pytest.mark.parametrize("iscrowd", [0, 1]) + @pytest.mark.parametrize( + "segmentation", + [ + {"counts": [2, 4], "size": [2, 3]}, + [[1.0, 0.0, 3.0, 0.0, 3.0, 2.0, 1.0, 2.0]], + ], + ) + def test_save__keeps_iscrowd( + self, tmp_path: Path, segmentation: object, iscrowd: int + ) -> None: + input_file = _create_coco_instance_segmentation_file( + tmp_path=tmp_path, segmentation=segmentation, iscrowd=iscrowd + ) + output_file = tmp_path / "output.json" + + COCOInstanceSegmentationOutput(output_file=output_file).save( + label_input=COCOInstanceSegmentationInput(input_file=input_file) + ) + + [annotation] = json.loads(output_file.read_text())["annotations"] + assert annotation["iscrowd"] == iscrowd + assert annotation["segmentation"] == segmentation + + +def _create_coco_instance_segmentation_file( + tmp_path: Path, segmentation: object, iscrowd: int +) -> Path: + data = { + "images": [{"id": 0, "file_name": "image.jpg", "width": 3, "height": 2}], + "categories": [{"id": 1, "name": "dog"}], + "annotations": [ + { + "image_id": 0, + "category_id": 1, + "bbox": [1.0, 0.0, 2.0, 2.0], + "iscrowd": iscrowd, + "segmentation": segmentation, + } + ], + } + coco_file = tmp_path / "instances.json" + coco_file.write_text(json.dumps(data)) + return coco_file diff --git a/tests/unit/formats/test_youtubevis.py b/tests/unit/formats/test_youtubevis.py index 0b6e3ec..e459f3f 100644 --- a/tests/unit/formats/test_youtubevis.py +++ b/tests/unit/formats/test_youtubevis.py @@ -118,6 +118,7 @@ def test_get_labels(self, tmp_path: Path) -> None: category=Category(id=1, name="cat"), segmentations=[expected_rle_segmentation, None], object_track_id=20, + is_crowd=True, ), SingleInstanceSegmentationTrack( category=Category(id=1, name="cat"), @@ -161,6 +162,25 @@ def test_import_export(self, tmp_path: Path) -> None: annotation_output == annotation_expected ), f"Annotations do not match. Output: {annotation_output}, Expected: {annotation_expected}" + def test_import_export__keeps_iscrowd(self, tmp_path: Path) -> None: + # The RLE track is not a crowd and the polygon track is a crowd. + input_file = _write_youtube_vis_instance_segmentation_json( + tmp_path / "instances.json" + ) + data = json.loads(input_file.read_text()) + data["annotations"][0]["iscrowd"] = 0 + data["annotations"][1]["iscrowd"] = 1 + input_file.write_text(json.dumps(data)) + label_input = YouTubeVISInstanceSegmentationTrackInput(input_file=input_file) + + output_path = tmp_path / "instances_out.json" + YouTubeVISInstanceSegmentationTrackOutput(output_file=output_path).save( + label_input=label_input + ) + + annotations = json.loads(output_path.read_text())["annotations"] + assert [annotation["iscrowd"] for annotation in annotations] == [0, 1] + def _write_youtube_vis_json(input_file: Path) -> Path: data = {