fix(dataset): make COCO annotation/image ids chainable across splits (#2267)
* fix(dataset): make COCO annotation/image ids chainable across splits (#768) Exporting train/valid/test splits with DetectionDataset.as_coco previously restarted image_id and annotation_id at 1 for every split, producing three JSON files whose ids collided and could not be safely merged into a single COCO collection. Adds optional starting_image_id and starting_annotation_id parameters to save_coco_annotations and DetectionDataset.as_coco (default 1 to preserve existing behavior) and returns a (next_image_id, next_annotation_id) tuple so callers can feed the result of one export straight into the next: next_image, next_ann = train.as_coco(annotations_path="train.json") next_image, next_ann = valid.as_coco( annotations_path="valid.json", starting_image_id=next_image, starting_annotation_id=next_ann, ) test.as_coco( annotations_path="test.json", starting_image_id=next_image, starting_annotation_id=next_ann, ) The images-only branch of as_coco (annotations_path=None) round-trips the starting ids unchanged so chaining still works there. Adds 4 regression tests covering defaults, custom starting ids, end-to-end three-split chaining with global uniqueness assertions, and the images-only round-trip. * docs: address review polish on COCO id-chaining * fix(dataset): align save_coco_annotations approximation_percentage default to 0.0 * docs(dataset): add one-line summary to save_coco_annotations docstring * docs: add changelog entry for COCO id chaining (PR #2267) * docs(dataset): document file_name uniqueness limitation in save_coco_annotations * feat(dataset): validate starting_image_id and starting_annotation_id >= 1 * docs(dataset): add Example section to save_coco_annotations docstring * docs(dataset): unpack final as_coco return value in chaining example * test(dataset): add COCO chaining tests and fix test helper for zero detections --------- Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com> Co-authored-by: Claude Code <noreply@anthropic.com>
This commit is contained in:
co-authored by
Jirka Borovec
Claude Code
parent
cb259065a5
commit
befdb7c661
+1
-1
@@ -7,7 +7,7 @@ date_modified: 2026-04-30
|
||||
|
||||
### UnReleased
|
||||
|
||||
-
|
||||
- Added [#2267](https://github.com/roboflow/supervision/pull/2267): [`DetectionDataset.as_coco`](https://supervision.roboflow.com/latest/datasets/core/#supervision.dataset.core.DetectionDataset.as_coco) and `save_coco_annotations` now accept `starting_image_id` and `starting_annotation_id` parameters (both default to `1`, preserving existing behavior) and return a `(next_image_id, next_annotation_id)` tuple. Feed the returned values into the next split's call to produce globally unique COCO ids across train/valid/test exports. Fixes id collisions reported in [#768](https://github.com/roboflow/supervision/issues/768). **Note**: the return type changes from `None` to `tuple[int, int]` — callers that assert `result is None` must be updated.
|
||||
|
||||
### 0.28.0 <small>Apr 30, 2026</small>
|
||||
|
||||
|
||||
@@ -609,7 +609,9 @@ class DetectionDataset(BaseDataset):
|
||||
min_image_area_percentage: float = 0.0,
|
||||
max_image_area_percentage: float = 1.0,
|
||||
approximation_percentage: float = 0.0,
|
||||
) -> None:
|
||||
starting_image_id: int = 1,
|
||||
starting_annotation_id: int = 1,
|
||||
) -> tuple[int, int]:
|
||||
"""
|
||||
Exports the dataset to COCO format. This method saves the
|
||||
images and their corresponding annotations in COCO format.
|
||||
@@ -645,19 +647,59 @@ class DetectionDataset(BaseDataset):
|
||||
to be removed from the input polygon,
|
||||
in the range [0, 1). This is useful for simplifying the annotations.
|
||||
Argument is used only for segmentation datasets.
|
||||
starting_image_id: First image id to assign in the exported file.
|
||||
Defaults to ``1``. Override when exporting multiple splits into
|
||||
a coordinated COCO collection so ids remain unique across the
|
||||
set (see example below).
|
||||
starting_annotation_id: First annotation id to assign in the
|
||||
exported file. Defaults to ``1``. Override for the same
|
||||
multi-split reason as ``starting_image_id``.
|
||||
|
||||
Returns:
|
||||
A ``(next_image_id, next_annotation_id)`` tuple containing the
|
||||
first unused ids after this export. Feed them straight back into
|
||||
``starting_image_id`` and ``starting_annotation_id`` on the next
|
||||
split so ids stay globally unique. When ``annotations_path`` is
|
||||
``None`` (images-only export) the starting ids are returned
|
||||
unchanged so chaining still composes.
|
||||
|
||||
Example:
|
||||
```python
|
||||
# Exporting train, valid, and test splits with non-colliding ids
|
||||
# so the three annotation files can later be merged into one COCO.
|
||||
next_image_id, next_annotation_id = train_ds.as_coco(
|
||||
images_directory_path="out/train/images",
|
||||
annotations_path="out/train/annotations.json",
|
||||
)
|
||||
next_image_id, next_annotation_id = valid_ds.as_coco(
|
||||
images_directory_path="out/valid/images",
|
||||
annotations_path="out/valid/annotations.json",
|
||||
starting_image_id=next_image_id,
|
||||
starting_annotation_id=next_annotation_id,
|
||||
)
|
||||
_, _ = test_ds.as_coco(
|
||||
images_directory_path="out/test/images",
|
||||
annotations_path="out/test/annotations.json",
|
||||
starting_image_id=next_image_id,
|
||||
starting_annotation_id=next_annotation_id,
|
||||
) # return value not needed — no further split
|
||||
```
|
||||
"""
|
||||
if images_directory_path is not None:
|
||||
save_dataset_images(
|
||||
dataset=self, images_directory_path=images_directory_path
|
||||
)
|
||||
if annotations_path is not None:
|
||||
save_coco_annotations(
|
||||
return save_coco_annotations(
|
||||
dataset=self,
|
||||
annotation_path=annotations_path,
|
||||
min_image_area_percentage=min_image_area_percentage,
|
||||
max_image_area_percentage=max_image_area_percentage,
|
||||
approximation_percentage=approximation_percentage,
|
||||
starting_image_id=starting_image_id,
|
||||
starting_annotation_id=starting_annotation_id,
|
||||
)
|
||||
return starting_image_id, starting_annotation_id
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -372,8 +372,68 @@ def save_coco_annotations(
|
||||
annotation_path: str,
|
||||
min_image_area_percentage: float = 0.0,
|
||||
max_image_area_percentage: float = 1.0,
|
||||
approximation_percentage: float = 0.75,
|
||||
) -> None:
|
||||
approximation_percentage: float = 0.0,
|
||||
starting_image_id: int = 1,
|
||||
starting_annotation_id: int = 1,
|
||||
) -> tuple[int, int]:
|
||||
"""Save a DetectionDataset to a COCO-format ``annotations.json`` file.
|
||||
|
||||
Args:
|
||||
dataset: The DetectionDataset to write.
|
||||
annotation_path: Output path for the COCO ``annotations.json``.
|
||||
min_image_area_percentage: Lower bound on detection area / image area;
|
||||
used only for segmentation datasets.
|
||||
max_image_area_percentage: Upper bound on detection area / image area;
|
||||
used only for segmentation datasets.
|
||||
approximation_percentage: Polygon-simplification ratio in ``[0, 1)``;
|
||||
used only for segmentation datasets.
|
||||
starting_image_id: First image id to assign in the exported file.
|
||||
Defaults to ``1``. Override when exporting multiple splits into
|
||||
a coordinated COCO collection so ids remain unique across the set.
|
||||
starting_annotation_id: First annotation id to assign in the exported
|
||||
file. Defaults to ``1``. Override for the same multi-split reason
|
||||
as ``starting_image_id``.
|
||||
|
||||
Returns:
|
||||
A ``(next_image_id, next_annotation_id)`` tuple. The returned values
|
||||
are one greater than the highest ids written, so they can be fed
|
||||
directly back into ``starting_image_id`` and ``starting_annotation_id``
|
||||
when exporting another split into a coordinated COCO collection
|
||||
(see ``DetectionDataset.as_coco`` for the chaining pattern). When the
|
||||
dataset is empty the starting ids are returned unchanged.
|
||||
|
||||
.. note::
|
||||
This function ensures globally unique integer ``id`` values across
|
||||
splits. It does **not** ensure unique ``file_name`` values — the
|
||||
``file_name`` field is set to the bare image basename, so splits
|
||||
that share filenames (e.g. ``000001.jpg`` in both train and valid)
|
||||
will have duplicate ``file_name`` values when their COCO files are
|
||||
merged. Use distinct output directories or rename images before
|
||||
merging if downstream tools require unique ``file_name`` keys.
|
||||
|
||||
Example:
|
||||
```python
|
||||
import supervision as sv
|
||||
from supervision.dataset.formats.coco import save_coco_annotations
|
||||
|
||||
ds = sv.DetectionDataset.from_yolo(
|
||||
images_directory_path="train/images",
|
||||
annotations_directory_path="train/labels",
|
||||
data_yaml_path="data.yaml",
|
||||
)
|
||||
next_img_id, next_ann_id = save_coco_annotations(
|
||||
dataset=ds, annotation_path="out/train/annotations.json"
|
||||
)
|
||||
# next_img_id and next_ann_id are the first unused ids — pass them
|
||||
# to the next split to keep ids globally unique across files.
|
||||
```
|
||||
"""
|
||||
if starting_image_id < 1 or starting_annotation_id < 1:
|
||||
raise ValueError(
|
||||
"starting_image_id and starting_annotation_id must be >= 1 "
|
||||
"(COCO spec requires 1-indexed ids); "
|
||||
f"got {starting_image_id=}, {starting_annotation_id=}"
|
||||
)
|
||||
Path(annotation_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
licenses = [
|
||||
{
|
||||
@@ -387,7 +447,7 @@ def save_coco_annotations(
|
||||
coco_images = []
|
||||
coco_categories = classes_to_coco_categories(classes=dataset.classes)
|
||||
|
||||
image_id, annotation_id = 1, 1
|
||||
image_id, annotation_id = starting_image_id, starting_annotation_id
|
||||
for image_path, image, annotation in dataset:
|
||||
image_height, image_width, _ = image.shape
|
||||
image_name = f"{Path(image_path).stem}{Path(image_path).suffix}"
|
||||
@@ -421,3 +481,4 @@ def save_coco_annotations(
|
||||
"annotations": coco_annotations,
|
||||
}
|
||||
save_json_file(annotation_dict, file_path=annotation_path)
|
||||
return image_id, annotation_id
|
||||
|
||||
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
import json
|
||||
from contextlib import ExitStack as DoesNotRaise
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
@@ -15,6 +16,7 @@ from supervision.dataset.formats.coco import (
|
||||
detections_to_coco_annotations,
|
||||
group_coco_annotations_by_image_id,
|
||||
load_coco_annotations,
|
||||
save_coco_annotations,
|
||||
)
|
||||
|
||||
|
||||
@@ -1447,3 +1449,188 @@ class TestFromCocoMasks:
|
||||
annotation = dataset.annotations[str(images_directory / "image.jpg")]
|
||||
assert annotation.mask is not None
|
||||
assert annotation.mask.shape == (1, 5, 5)
|
||||
|
||||
|
||||
# --- save_coco_annotations: cross-split id chaining (regression for #768) ---
|
||||
|
||||
|
||||
def _tiny_detection_dataset(
|
||||
tmp_path, prefix: str, num_images: int, dets_per_image: int
|
||||
) -> DetectionDataset:
|
||||
"""Build a DetectionDataset of ``num_images`` 10x10 RGB images on disk,
|
||||
each holding ``dets_per_image`` 1x1 detections of class 0. Image content
|
||||
is irrelevant; only the per-image Detections drive the COCO write path."""
|
||||
classes = ["object"]
|
||||
image_paths: list[str] = []
|
||||
annotations: dict[str, Detections] = {}
|
||||
for i in range(num_images):
|
||||
path = str(tmp_path / f"{prefix}_{i}.jpg")
|
||||
assert cv2.imwrite(path, np.zeros((10, 10, 3), dtype=np.uint8))
|
||||
image_paths.append(path)
|
||||
xyxy = np.array(
|
||||
[[float(j), 0.0, float(j) + 1.0, 1.0] for j in range(dets_per_image)],
|
||||
dtype=float,
|
||||
).reshape(-1, 4)
|
||||
annotations[path] = Detections(
|
||||
xyxy=xyxy,
|
||||
class_id=np.zeros(dets_per_image, dtype=int),
|
||||
confidence=np.ones(dets_per_image, dtype=float),
|
||||
)
|
||||
return DetectionDataset(
|
||||
classes=classes, images=image_paths, annotations=annotations
|
||||
)
|
||||
|
||||
|
||||
def _read_ids(annotation_path) -> tuple[list[int], list[int]]:
|
||||
with open(annotation_path) as f:
|
||||
payload = json.load(f)
|
||||
image_ids = [img["id"] for img in payload["images"]]
|
||||
annotation_ids = [ann["id"] for ann in payload["annotations"]]
|
||||
return image_ids, annotation_ids
|
||||
|
||||
|
||||
def test_save_coco_annotations_defaults_start_at_one(tmp_path):
|
||||
dataset = _tiny_detection_dataset(tmp_path, "img", num_images=2, dets_per_image=3)
|
||||
annotation_path = tmp_path / "annotations.json"
|
||||
|
||||
next_image_id, next_annotation_id = save_coco_annotations(
|
||||
dataset=dataset, annotation_path=str(annotation_path)
|
||||
)
|
||||
|
||||
image_ids, annotation_ids = _read_ids(annotation_path)
|
||||
assert image_ids == [1, 2]
|
||||
assert annotation_ids == [1, 2, 3, 4, 5, 6]
|
||||
# Returned ids are one greater than the highest written, ready to chain.
|
||||
assert next_image_id == 3
|
||||
assert next_annotation_id == 7
|
||||
|
||||
|
||||
def test_save_coco_annotations_respects_starting_ids(tmp_path):
|
||||
dataset = _tiny_detection_dataset(tmp_path, "img", num_images=2, dets_per_image=2)
|
||||
annotation_path = tmp_path / "annotations.json"
|
||||
|
||||
next_image_id, next_annotation_id = save_coco_annotations(
|
||||
dataset=dataset,
|
||||
annotation_path=str(annotation_path),
|
||||
starting_image_id=100,
|
||||
starting_annotation_id=500,
|
||||
)
|
||||
|
||||
image_ids, annotation_ids = _read_ids(annotation_path)
|
||||
assert image_ids == [100, 101]
|
||||
assert annotation_ids == [500, 501, 502, 503]
|
||||
assert next_image_id == 102
|
||||
assert next_annotation_id == 504
|
||||
|
||||
|
||||
def test_as_coco_chains_ids_across_splits_without_collision(tmp_path):
|
||||
"""Regression for #768: exporting train/valid/test splits with the
|
||||
returned ids fed forward yields globally unique image and annotation ids."""
|
||||
train = _tiny_detection_dataset(tmp_path, "train", num_images=3, dets_per_image=2)
|
||||
valid = _tiny_detection_dataset(tmp_path, "valid", num_images=2, dets_per_image=4)
|
||||
test = _tiny_detection_dataset(tmp_path, "test", num_images=1, dets_per_image=5)
|
||||
|
||||
train_path = tmp_path / "train.json"
|
||||
valid_path = tmp_path / "valid.json"
|
||||
test_path = tmp_path / "test.json"
|
||||
|
||||
next_image_id, next_annotation_id = train.as_coco(annotations_path=str(train_path))
|
||||
next_image_id, next_annotation_id = valid.as_coco(
|
||||
annotations_path=str(valid_path),
|
||||
starting_image_id=next_image_id,
|
||||
starting_annotation_id=next_annotation_id,
|
||||
)
|
||||
test.as_coco(
|
||||
annotations_path=str(test_path),
|
||||
starting_image_id=next_image_id,
|
||||
starting_annotation_id=next_annotation_id,
|
||||
)
|
||||
|
||||
all_image_ids: list[int] = []
|
||||
all_annotation_ids: list[int] = []
|
||||
for path in (train_path, valid_path, test_path):
|
||||
image_ids, annotation_ids = _read_ids(path)
|
||||
all_image_ids.extend(image_ids)
|
||||
all_annotation_ids.extend(annotation_ids)
|
||||
|
||||
assert len(all_image_ids) == len(set(all_image_ids)), (
|
||||
"image ids collide across splits"
|
||||
)
|
||||
assert len(all_annotation_ids) == len(set(all_annotation_ids)), (
|
||||
"annotation ids collide across splits"
|
||||
)
|
||||
# Concrete chained values.
|
||||
assert all_image_ids == [1, 2, 3, 4, 5, 6]
|
||||
assert all_annotation_ids == list(range(1, 6 + 8 + 5 + 1))
|
||||
|
||||
|
||||
def test_save_coco_annotations_empty_dataset_returns_starting_ids(tmp_path):
|
||||
"""An empty dataset writes a valid (but empty) COCO file and returns
|
||||
the starting ids unchanged so chaining still composes around it."""
|
||||
dataset = DetectionDataset(classes=["object"], images=[], annotations={})
|
||||
annotation_path = tmp_path / "annotations.json"
|
||||
|
||||
next_image_id, next_annotation_id = save_coco_annotations(
|
||||
dataset=dataset,
|
||||
annotation_path=str(annotation_path),
|
||||
starting_image_id=7,
|
||||
starting_annotation_id=42,
|
||||
)
|
||||
|
||||
image_ids, annotation_ids = _read_ids(annotation_path)
|
||||
assert image_ids == []
|
||||
assert annotation_ids == []
|
||||
assert next_image_id == 7
|
||||
assert next_annotation_id == 42
|
||||
|
||||
|
||||
def test_as_coco_without_annotations_path_returns_starting_ids(tmp_path):
|
||||
"""When only writing images, the starting ids round-trip unchanged so
|
||||
chaining still works in the images-only branch."""
|
||||
dataset = _tiny_detection_dataset(tmp_path, "img", num_images=2, dets_per_image=1)
|
||||
next_image_id, next_annotation_id = dataset.as_coco(
|
||||
images_directory_path=str(tmp_path / "imgs"),
|
||||
starting_image_id=42,
|
||||
starting_annotation_id=99,
|
||||
)
|
||||
assert next_image_id == 42
|
||||
assert next_annotation_id == 99
|
||||
|
||||
|
||||
def test_save_coco_annotations_annotation_image_id_references_correct_image(tmp_path):
|
||||
"""Every annotation's image_id must reference an image id present in the
|
||||
same file, even when a non-default starting_image_id is used."""
|
||||
dataset = _tiny_detection_dataset(tmp_path, "img", num_images=3, dets_per_image=2)
|
||||
annotation_path = tmp_path / "annotations.json"
|
||||
|
||||
save_coco_annotations(
|
||||
dataset=dataset,
|
||||
annotation_path=str(annotation_path),
|
||||
starting_image_id=100,
|
||||
starting_annotation_id=500,
|
||||
)
|
||||
|
||||
with open(annotation_path) as f:
|
||||
coco = json.load(f)
|
||||
image_id_set = {img["id"] for img in coco["images"]}
|
||||
annotation_image_ids = {ann["image_id"] for ann in coco["annotations"]}
|
||||
assert annotation_image_ids <= image_id_set, (
|
||||
"annotation image_id values reference unknown image ids"
|
||||
)
|
||||
|
||||
|
||||
def test_save_coco_annotations_zero_annotation_images(tmp_path):
|
||||
"""Dataset with images but zero detections per image: image ids are
|
||||
assigned sequentially but annotation list stays empty."""
|
||||
dataset = _tiny_detection_dataset(tmp_path, "img", num_images=2, dets_per_image=0)
|
||||
annotation_path = tmp_path / "annotations.json"
|
||||
|
||||
next_image_id, next_annotation_id = save_coco_annotations(
|
||||
dataset=dataset, annotation_path=str(annotation_path)
|
||||
)
|
||||
|
||||
image_ids, annotation_ids = _read_ids(annotation_path)
|
||||
assert image_ids == [1, 2]
|
||||
assert annotation_ids == []
|
||||
assert next_image_id == 3
|
||||
assert next_annotation_id == 1
|
||||
|
||||
Reference in New Issue
Block a user