Repository navigation
Keep the crowd flag in COCO and YouTube-VIS format classes - #94
lukas-lightly merged 2 commits into
Conversation
|
Could you include the steps you used to reproduce the AP of 1.0? When I loaded the exported JSON directly with |
|
You are right. The COCO output writes no annotation The script exports one RLE mask from a non-COCO input with Run it with
On main the missing 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
left a comment
There was a problem hiding this comment.
Thanks for sharing the script and updating the PR description. The PR looks good.
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.
iscrowdfrom 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 withsegmentation_type="rle", had no objects to evaluate.iscrowd. An RLE mask withiscrowd: 0failed withValueError: 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.COCOSingleInstanceSegmentationsubclass ofSingleInstanceSegmentationand newYouTubeVISSingleInstanceSegmentationTracksubclass ofSingleInstanceSegmentationTrack, each withis_crowd: bool = False. Both are exported fromlabelformat.formats.is_crowdfromiscrowd. COCO and YouTube-VIS output writeiscrowdas1or0fromis_crowd, and0for objects of the base classes.get_coco_segmentationreturns 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.
test_coco_inversenow expects the subclass.iscrowd: 0instead oftrue, 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?
iscrowd0 and 1 and with the JSON booleans of older files, a COCO round trip that keepsiscrowdfor both encodings, COCO and YouTube-VIS output of base class objects with RLE masks (iscrowd0), and a YouTube-VIS round trip with an RLE track that is not a crowd and a polygon track that is a crowd.iscrowdfrom the encoding again.test_coco_inverseexpect the subclasses, and the maskpair RLE test expectsiscrowd: 0.make all-checkspasses with 192 passed and 1 skipped, and so doespyteston Python 3.8 and 3.14."iscrowd": trueand AP -1.0. COCO output writes no annotationidorareayet (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.