Skip to content

Keep the crowd flag in COCO and YouTube-VIS format classes - #94

Merged
lukas-lightly merged 2 commits into
lightly-ai:mainfrom
lorinczszabolcs:keep-crowd-flag-in-format-subclasses
Nov 25, 2026
Merged

lukas-lightly merged 2 commits into
lightly-ai:mainfrom
lorinczszabolcs:keep-crowd-flag-in-format-subclasses

Conversation

@lorinczszabolcs

@lorinczszabolcs lorinczszabolcs commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

What has changed and why?

Proposed fix for lightly-ai/lightly-studio#2959. Replaces #93 with the approach agreed there. The crowd flag stays in the COCO and YouTube-VIS format code, and the label base classes do not change.

  • COCO and YouTube-VIS output set iscrowd from the mask encoding, so every RLE mask was written as a crowd. COCO evaluation ignores crowds, so exports from tools that store single objects as RLE, such as LightlyStudio or maskpair with segmentation_type="rle", had no objects to evaluate.
  • COCO input chose the decoder from iscrowd. An RLE mask with iscrowd: 0 failed with ValueError: could not convert string to float. COCO input now chooses the decoder from the segmentation type (dict for RLE, list for polygons), as YouTube-VIS input already does.
  • New COCOSingleInstanceSegmentation subclass of SingleInstanceSegmentation and new YouTubeVISSingleInstanceSegmentationTrack subclass of SingleInstanceSegmentationTrack, each with is_crowd: bool = False. Both are exported from labelformat.formats.
  • COCO and YouTube-VIS input return these subclasses with is_crowd from iscrowd. COCO and YouTube-VIS output write iscrowd as 1 or 0 from is_crowd, and 0 for objects of the base classes.
  • get_coco_segmentation returns only the segmentation and the bounding box, because the crowd flag does not come from the encoding. The function is not exported, and its only callers are the COCO and YouTube-VIS output.

The PR changes two things that users can see.

  • Objects from COCO and YouTube-VIS input are instances of the subclasses. Dataclass equality compares the class, so they are not equal to base class objects with the same fields. test_coco_inverse now expects the subclass.
  • Masks from other inputs, for example maskpair with RLE, are written with iscrowd: 0 instead of true, because each mask is one object.

Files with "iscrowd": true, as labelformat 0.1.17 and earlier write them, still read as crowds.

How has it been tested?

  • New tests cover COCO input for RLE and polygons with iscrowd 0 and 1 and with the JSON booleans of older files, a COCO round trip that keeps iscrowd for both encodings, COCO and YouTube-VIS output of base class objects with RLE masks (iscrowd 0), and a YouTube-VIS round trip with an RLE track that is not a crowd and a polygon track that is a crowd.
  • The new output tests fail if the output sets iscrowd from the encoding again.
  • In the updated tests, the YouTube-VIS input test and test_coco_inverse expect the subclasses, and the maskpair RLE test expects iscrowd: 0.
  • make all-checks passes with 192 passed and 1 skipped, and so does pytest on Python 3.8 and 3.14.
  • In a pycocotools check, an RLE mask from a non-COCO input, written with COCO output and evaluated against itself, gives segm AP 1.0 on this branch. On main the same file has "iscrowd": true and AP -1.0. COCO output writes no annotation id or area yet (COCO outputs omit annotation id and area, so pycocotools can't load them #97), so the check script adds both before the evaluation. The script is in the PR comments.

@lukas-lightly

Copy link
Copy Markdown
Contributor

Could you include the steps you used to reproduce the AP of 1.0? When I loaded the exported JSON directly with pycocotools.COCO(), it raised KeyError: 'id' while indexing the annotations. The exporter also omits area. A short snippet showing how you prepared the ground truth and predictions would make the comparison easy to reproduce.

@lorinczszabolcs

Copy link
Copy Markdown
Contributor Author

You are right. The COCO output writes no annotation id or area, so COCO() cannot load the exported file as it is. My check added both fields before the evaluation, and the PR description did not say that. Sorry for the confusion.

The script exports one RLE mask from a non-COCO input with COCOInstanceSegmentationOutput. It then adds id (sequential from 1) and area (the RLE pixel count from pycocotools.mask.area) and evaluates the masks against themselves. These are the same rules that #97 proposes for the output. Neither value can change the AP here, because the headline AP uses the area range "all".

Run it with uv run --with pycocotools python check_pycocotools.py out.json.

  • On this branch (0b5fb2c), iscrowd is written as 0 and the AP is 1.0 (pycocotools prints 0.9999999999999998).
  • On main (0601ca3), iscrowd is written as true and the AP is -1.0, because pycocotools ignores the crowd mask and has nothing to evaluate.

On main the missing area does not show, because pycocotools does not read the area of ignored crowd annotations. With this PR the mask is no longer a crowd, so pycocotools reads area and raises KeyError: 'area' when it is missing. For pycocotools users this PR therefore also needs #97. I updated the testing section of the description to say this.

check_pycocotools.py
"""Export RLE masks from a non-COCO input to COCO and evaluate them with pycocotools."""

import json
import sys
from pathlib import Path
from typing import Iterable

import numpy as np
from pycocotools import mask as mask_utils
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval

from labelformat.formats import COCOInstanceSegmentationOutput
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.instance_segmentation import (
    ImageInstanceSegmentation,
    InstanceSegmentationInput,
    SingleInstanceSegmentation,
)


class _MaskInput(InstanceSegmentationInput):
    @staticmethod
    def add_cli_arguments(parser) -> None:
        pass

    def get_categories(self) -> Iterable[Category]:
        return [Category(id=1, name="dog")]

    def get_images(self) -> Iterable[Image]:
        return [Image(id=0, filename="image.jpg", width=20, height=10)]

    def get_labels(self) -> Iterable[ImageInstanceSegmentation]:
        mask = np.zeros((10, 20), dtype=int)
        mask[2:6, 3:9] = 1
        segmentation = BinaryMaskSegmentation.from_binary_mask(
            binary_mask=mask, bounding_box=BoundingBox(xmin=3, ymin=2, xmax=9, ymax=6)
        )
        return [
            ImageInstanceSegmentation(
                image=Image(id=0, filename="image.jpg", width=20, height=10),
                objects=[
                    SingleInstanceSegmentation(
                        category=Category(id=1, name="dog"), segmentation=segmentation
                    )
                ],
            )
        ]


out = Path(sys.argv[1])
COCOInstanceSegmentationOutput(output_file=out).save(label_input=_MaskInput())
data = json.loads(out.read_text())
print("iscrowd written:", [a["iscrowd"] for a in data["annotations"]])
# COCO output writes no annotation "id" or "area" yet (#97), so add them here.
for i, a in enumerate(data["annotations"]):
    a["id"] = i + 1
    rle = mask_utils.frPyObjects(a["segmentation"], *a["segmentation"]["size"])
    a["area"] = float(mask_utils.area(rle))
out.write_text(json.dumps(data))
gt = COCO(str(out))
# The predictions are the ground truth masks with score 1.0.
dets = [dict(a, score=1.0) for a in data["annotations"]]
dt = gt.loadRes(dets)
ev = COCOeval(gt, dt, iouType="segm")
ev.evaluate(); ev.accumulate(); ev.summarize()
print("AP:", ev.stats[0])

@lukas-lightly lukas-lightly left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for sharing the script and updating the PR description. The PR looks good.

@lukas-lightly
lukas-lightly enabled auto-merge (squash) November 25, 2026 14:14
@lukas-lightly
lukas-lightly merged commit 7dd9035 into lightly-ai:main Nov 25, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants