Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/labelformat/formats/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
COCOInstanceSegmentationOutput,
COCOObjectDetectionInput,
COCOObjectDetectionOutput,
COCOSingleInstanceSegmentation,
)
from labelformat.formats.cvat import CVATObjectDetectionInput, CVATObjectDetectionOutput
from labelformat.formats.kitti import (
Expand Down Expand Up @@ -74,6 +75,7 @@
YouTubeVISInstanceSegmentationTrackInput,
YouTubeVISInstanceSegmentationTrackOutput,
YouTubeVISObjectDetectionTrackInput,
YouTubeVISSingleInstanceSegmentationTrack,
)

__all__ = [
Expand All @@ -82,6 +84,7 @@
"COCOInstanceSegmentationOutput",
"COCOObjectDetectionInput",
"COCOObjectDetectionOutput",
"COCOSingleInstanceSegmentation",
"CVATObjectDetectionInput",
"CVATObjectDetectionOutput",
"KittiObjectDetectionInput",
Expand Down Expand Up @@ -121,4 +124,5 @@
"YouTubeVISInstanceSegmentationTrackInput",
"YouTubeVISInstanceSegmentationTrackOutput",
"YouTubeVISObjectDetectionTrackInput",
"YouTubeVISSingleInstanceSegmentationTrack",
]
37 changes: 29 additions & 8 deletions src/labelformat/formats/coco.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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(
Expand Down Expand Up @@ -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)
Expand Down
5 changes: 1 addition & 4 deletions src/labelformat/formats/coco_segmentation_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)}")
27 changes: 20 additions & 7 deletions src/labelformat/formats/youtubevis.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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]
Expand All @@ -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,
Expand Down
19 changes: 18 additions & 1 deletion tests/integration/instance_segmentation/test_inverse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/test_maskpair_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]

Expand Down
Loading
Loading