Skip to content
Closed
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
16 changes: 10 additions & 6 deletions src/labelformat/formats/coco.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand All @@ -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(
Expand Down Expand Up @@ -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)
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)}")
8 changes: 3 additions & 5 deletions src/labelformat/formats/youtubevis.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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]
Expand All @@ -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,
Expand Down
1 change: 1 addition & 0 deletions src/labelformat/model/instance_segmentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
class SingleInstanceSegmentation:
category: Category
segmentation: MultiPolygon | BinaryMaskSegmentation
is_crowd: bool = False


@dataclass(frozen=True)
Expand Down
1 change: 1 addition & 0 deletions src/labelformat/model/instance_segmentation_track.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
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
90 changes: 89 additions & 1 deletion tests/unit/formats/test_coco.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
20 changes: 20 additions & 0 deletions tests/unit/formats/test_youtubevis.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down Expand Up @@ -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 = {
Expand Down