From 0b5fb2c9347095a9e97dec2075c8b193318d52e8 Mon Sep 17 00:00:00 2001 From: Szabolcs Botond Lorincz Molnar <13637835+lorinczszabolcs@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:34:30 +0100 Subject: [PATCH] Keep the crowd flag in COCO and YouTube-VIS format classes --- src/labelformat/formats/__init__.py | 4 + src/labelformat/formats/coco.py | 37 +++-- .../formats/coco_segmentation_helpers.py | 5 +- src/labelformat/formats/youtubevis.py | 27 +++- .../instance_segmentation/test_inverse.py | 19 ++- .../integration/test_maskpair_integration.py | 2 +- tests/unit/formats/test_coco.py | 126 +++++++++++++++++- tests/unit/formats/test_youtubevis.py | 81 ++++++++++- 8 files changed, 277 insertions(+), 24 deletions(-) diff --git a/src/labelformat/formats/__init__.py b/src/labelformat/formats/__init__.py index 0175a75..c675116 100644 --- a/src/labelformat/formats/__init__.py +++ b/src/labelformat/formats/__init__.py @@ -4,6 +4,7 @@ COCOInstanceSegmentationOutput, COCOObjectDetectionInput, COCOObjectDetectionOutput, + COCOSingleInstanceSegmentation, ) from labelformat.formats.cvat import CVATObjectDetectionInput, CVATObjectDetectionOutput from labelformat.formats.kitti import ( @@ -74,6 +75,7 @@ YouTubeVISInstanceSegmentationTrackInput, YouTubeVISInstanceSegmentationTrackOutput, YouTubeVISObjectDetectionTrackInput, + YouTubeVISSingleInstanceSegmentationTrack, ) __all__ = [ @@ -82,6 +84,7 @@ "COCOInstanceSegmentationOutput", "COCOObjectDetectionInput", "COCOObjectDetectionOutput", + "COCOSingleInstanceSegmentation", "CVATObjectDetectionInput", "CVATObjectDetectionOutput", "KittiObjectDetectionInput", @@ -121,4 +124,5 @@ "YouTubeVISInstanceSegmentationTrackInput", "YouTubeVISInstanceSegmentationTrackOutput", "YouTubeVISObjectDetectionTrackInput", + "YouTubeVISSingleInstanceSegmentationTrack", ] diff --git a/src/labelformat/formats/coco.py b/src/labelformat/formats/coco.py index fbde286..023f4bb 100644 --- a/src/labelformat/formats/coco.py +++ b/src/labelformat/formats/coco.py @@ -2,8 +2,9 @@ import json from argparse import ArgumentParser +from dataclasses import dataclass from pathlib import Path -from typing import Dict, Iterable, List +from typing import Dict, Iterable, List, cast import fsspec @@ -36,6 +37,17 @@ from labelformat.types import JsonDict, ParseError, PathLike +@dataclass(frozen=True) +class COCOSingleInstanceSegmentation(SingleInstanceSegmentation): + """Instance segmentation with the COCO crowd flag. + + COCO input returns this class, so that COCO output can write the crowd flag back. + COCO output writes `iscrowd` 0 for objects of other classes. + """ + + is_crowd: bool = False + + class _COCOBaseInput: @staticmethod def add_cli_arguments(parser: ArgumentParser) -> None: @@ -113,15 +125,20 @@ def get_labels(self) -> Iterable[ImageInstanceSegmentation]: image_id_to_annotations[ann["image_id"]].append(ann) for image_id, annotations in image_id_to_annotations.items(): - objects = [] + objects: list[SingleInstanceSegmentation] = [] for ann in annotations: if "segmentation" not in ann: raise ParseError(f"Segmentation missing for image id {image_id}") segmentation: MultiPolygon | BinaryMaskSegmentation - if ann["iscrowd"] == 1: + # The encoding of the segmentation sets the decoder. The crowd flag + # does not, because COCO also stores single objects as RLE. + if isinstance(ann["segmentation"], dict): segmentation = ( segmentation_helpers.coco_segmentation_to_binary_mask_rle( - segmentation=ann["segmentation"], bbox=ann["bbox"] + segmentation=cast( + COCOInstanceSegmentationRLE, ann["segmentation"] + ), + bbox=ann["bbox"], ) ) else: @@ -131,9 +148,10 @@ def get_labels(self) -> Iterable[ImageInstanceSegmentation]: ) ) objects.append( - SingleInstanceSegmentation( + COCOSingleInstanceSegmentation( category=category_id_to_category[ann["category_id"]], segmentation=segmentation, + is_crowd=bool(ann["iscrowd"]), ) ) yield ImageInstanceSegmentation( @@ -194,14 +212,17 @@ 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 + ) + is_crowd = ( + isinstance(obj, COCOSingleInstanceSegmentation) and obj.is_crowd ) annotation = { "image_id": label.image.id, "category_id": obj.category.id, "bbox": bbox, - "iscrowd": is_crowd, + "iscrowd": int(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..f0cf039 100644 --- a/src/labelformat/formats/youtubevis.py +++ b/src/labelformat/formats/youtubevis.py @@ -2,6 +2,7 @@ import json from argparse import ArgumentParser +from dataclasses import dataclass from pathlib import Path from typing import Dict, Iterable, List, cast @@ -32,6 +33,17 @@ from labelformat.types import JsonDict +@dataclass(frozen=True) +class YouTubeVISSingleInstanceSegmentationTrack(SingleInstanceSegmentationTrack): + """Instance segmentation track with the YouTube-VIS crowd flag. + + YouTube-VIS input returns this class, so that YouTube-VIS output can write the crowd + flag back. YouTube-VIS output writes `iscrowd` 0 for objects of other classes. + """ + + is_crowd: bool = False + + class _YouTubeVISBaseInput: @staticmethod def add_cli_arguments(parser: ArgumentParser) -> None: @@ -113,14 +125,15 @@ def get_labels(self) -> Iterable[VideoInstanceSegmentationTrack]: for video_id, tracks in video_id_to_tracks.items(): video = video_id_to_video[video_id] - objects = [] + objects: list[SingleInstanceSegmentationTrack] = [] for track in tracks: segmentations = _get_object_track_segmentations(ann=track) objects.append( - SingleInstanceSegmentationTrack( + YouTubeVISSingleInstanceSegmentationTrack( category=category_id_to_category[track["category_id"]], segmentations=segmentations, object_track_id=track.get("id"), + is_crowd=bool(track.get("iscrowd", 0)), ) ) yield VideoInstanceSegmentationTrack( @@ -201,16 +214,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 +244,10 @@ def _get_output_annotations_dict( "bboxes": bboxes_list, "segmentations": segmentations_list, "areas": areas_list, - "iscrowd": iscrowd, + "iscrowd": int( + isinstance(obj, YouTubeVISSingleInstanceSegmentationTrack) + and obj.is_crowd + ), "height": height, "width": width, "length": length, diff --git a/tests/integration/instance_segmentation/test_inverse.py b/tests/integration/instance_segmentation/test_inverse.py index b6ffd46..39c5bf4 100644 --- a/tests/integration/instance_segmentation/test_inverse.py +++ b/tests/integration/instance_segmentation/test_inverse.py @@ -5,11 +5,13 @@ from labelformat.formats.coco import ( COCOInstanceSegmentationInput, COCOInstanceSegmentationOutput, + COCOSingleInstanceSegmentation, ) from labelformat.formats.yolov8 import ( YOLOv8InstanceSegmentationInput, YOLOv8InstanceSegmentationOutput, ) +from labelformat.model.instance_segmentation import ImageInstanceSegmentation from labelformat.model.multipolygon import MultiPolygon from ...simple_instance_segmentation_label_input import ( @@ -25,7 +27,22 @@ def test_coco_inverse(tmp_path: Path) -> None: label_input=start_label_input ) end_label_input = COCOInstanceSegmentationInput(input_file=tmp_path / "train.json") - assert list(start_label_input.get_labels()) == list(end_label_input.get_labels()) + # COCO input returns its own class with the crowd flag. No object is a crowd. + expected_labels = [ + ImageInstanceSegmentation( + image=label.image, + objects=[ + COCOSingleInstanceSegmentation( + category=obj.category, + segmentation=obj.segmentation, + is_crowd=False, + ) + for obj in label.objects + ], + ) + for label in start_label_input.get_labels() + ] + assert list(end_label_input.get_labels()) == expected_labels def test_yolov8_inverse(tmp_path: Path, mocker: MockerFixture) -> None: 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..ff3d70b 100644 --- a/tests/unit/formats/test_coco.py +++ b/tests/unit/formats/test_coco.py @@ -3,16 +3,27 @@ import pytest -from labelformat.formats.coco import COCOObjectDetectionInput, COCOObjectDetectionOutput +from labelformat.formats.coco import ( + COCOInstanceSegmentationInput, + COCOInstanceSegmentationOutput, + COCOObjectDetectionInput, + COCOObjectDetectionOutput, + COCOSingleInstanceSegmentation, +) +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, ) from ... import simple_object_detection_label_input +from ...simple_instance_segmentation_label_input import ( + SimpleInstanceSegmentationInputWithBinaryMask, +) def _create_coco_file(tmp_path: Path, with_score: bool) -> Path: @@ -99,3 +110,116 @@ 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, COCOSingleInstanceSegmentation) + 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, COCOSingleInstanceSegmentation) + 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) + + @pytest.mark.parametrize("iscrowd", [False, True]) + def test_get_labels__boolean_iscrowd(self, tmp_path: Path, iscrowd: bool) -> None: + # labelformat 0.1.17 and earlier write iscrowd as a JSON boolean. + 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, COCOSingleInstanceSegmentation) + assert obj.is_crowd == iscrowd + + +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 test_save__other_input_is_not_crowd(self, tmp_path: Path) -> None: + # The input has one polygon and one binary mask, both without a crowd flag. + output_file = tmp_path / "output.json" + + COCOInstanceSegmentationOutput(output_file=output_file).save( + label_input=SimpleInstanceSegmentationInputWithBinaryMask() + ) + + annotations = json.loads(output_file.read_text())["annotations"] + assert [type(annotation["segmentation"]) for annotation in annotations] == [ + list, + dict, + ] + assert [annotation["iscrowd"] for annotation in annotations] == [0, 0] + + +def _create_coco_instance_segmentation_file( + tmp_path: Path, segmentation: object, iscrowd: object +) -> 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..b7fc73c 100644 --- a/tests/unit/formats/test_youtubevis.py +++ b/tests/unit/formats/test_youtubevis.py @@ -1,5 +1,7 @@ import json +from argparse import ArgumentParser from pathlib import Path +from typing import Iterable import numpy as np @@ -7,6 +9,7 @@ YouTubeVISInstanceSegmentationTrackInput, YouTubeVISInstanceSegmentationTrackOutput, YouTubeVISObjectDetectionTrackInput, + YouTubeVISSingleInstanceSegmentationTrack, ) from labelformat.model.binary_mask_segmentation import ( BinaryMaskSegmentation, @@ -15,6 +18,7 @@ from labelformat.model.bounding_box import BoundingBox from labelformat.model.category import Category from labelformat.model.instance_segmentation_track import ( + InstanceSegmentationTrackInput, SingleInstanceSegmentationTrack, VideoInstanceSegmentationTrack, ) @@ -114,18 +118,20 @@ def test_get_labels(self, tmp_path: Path) -> None: number_of_frames=2, ), objects=[ - SingleInstanceSegmentationTrack( + YouTubeVISSingleInstanceSegmentationTrack( category=Category(id=1, name="cat"), segmentations=[expected_rle_segmentation, None], object_track_id=20, + is_crowd=True, ), - SingleInstanceSegmentationTrack( + YouTubeVISSingleInstanceSegmentationTrack( category=Category(id=1, name="cat"), segmentations=[ expected_polygon_segmentation, None, ], object_track_id=21, + is_crowd=False, ), ], ) @@ -161,6 +167,77 @@ 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 fixture has a crowd RLE track and a polygon track. Here 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)) + + output_path = tmp_path / "instances_out.json" + YouTubeVISInstanceSegmentationTrackOutput(output_file=output_path).save( + label_input=YouTubeVISInstanceSegmentationTrackInput(input_file=input_file) + ) + + annotations = json.loads(output_path.read_text())["annotations"] + assert [type(annotation["segmentations"][0]) for annotation in annotations] == [ + dict, + list, + ] + assert [annotation["iscrowd"] for annotation in annotations] == [0, 1] + + +class TestYouTubeVISInstanceSegmentationTrackOutput: + def test_save__other_input_is_not_crowd(self, tmp_path: Path) -> None: + output_path = tmp_path / "instances_out.json" + + YouTubeVISInstanceSegmentationTrackOutput(output_file=output_path).save( + label_input=_RLETrackInput() + ) + + [annotation] = json.loads(output_path.read_text())["annotations"] + assert isinstance(annotation["segmentations"][0], dict) + assert annotation["iscrowd"] == 0 + + +class _RLETrackInput(InstanceSegmentationTrackInput): + """Input with one binary mask track and no crowd flag.""" + + _video = Video(id=5, filename="video1", width=3, height=2, number_of_frames=1) + _category = Category(id=1, name="cat") + + @staticmethod + def add_cli_arguments(parser: ArgumentParser) -> None: + pass + + def get_categories(self) -> Iterable[Category]: + return [self._category] + + def get_videos(self) -> Iterable[Video]: + return [self._video] + + def get_labels(self) -> Iterable[VideoInstanceSegmentationTrack]: + mask = BinaryMaskSegmentation.from_binary_mask( + binary_mask=np.array([[0, 1, 1], [0, 1, 1]], dtype=int), + bounding_box=BoundingBox(xmin=1.0, ymin=0.0, xmax=3.0, ymax=2.0), + ) + return [ + VideoInstanceSegmentationTrack( + video=self._video, + objects=[ + SingleInstanceSegmentationTrack( + category=self._category, + segmentations=[mask], + object_track_id=20, + ) + ], + ) + ] + def _write_youtube_vis_json(input_file: Path) -> Path: data = {