Skip to content
Open
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
12 changes: 9 additions & 3 deletions src/labelformat/formats/coco.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
}
Expand Down
34 changes: 34 additions & 0 deletions src/labelformat/formats/coco_segmentation_helpers.py
Original file line number Diff line number Diff line change
@@ -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 (
Expand Down Expand Up @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ def test_coco_to_coco(tmp_path: Path) -> None:
# - <image>.license
# - <image>.flickr_url
# - <image>.coco_url
# The output writes new annotation ids and computes the area itself:
# - <annotation>.id
# - <annotation>.area
del expected_json["info"]
Expand All @@ -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)
6 changes: 4 additions & 2 deletions tests/integration/object_detection/test_object_detection.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ def test_coco_to_coco(tmp_path: Path) -> None:
# - licenses
# - <category>.supercategory
# - <image>.date_captured
# The output writes new annotation ids and computes the area itself:
# - <annotation>.id
# - <annotation>.area
# - <annotation>.iscrowd
del expected_json["info"]
del expected_json["licenses"]
for category in expected_json["categories"]:
Expand All @@ -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


Expand Down
61 changes: 61 additions & 0 deletions tests/unit/formats/test_coco.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 = [
Expand Down Expand Up @@ -96,21 +99,52 @@ 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:
expected_annotations[0]["score"] = 0.4
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])
Expand Down Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions tests/unit/formats/test_coco_segmentation_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading