roboflow/supervision · error · ValueError

COCO annotation refers to image {image_name}, which produces

Error message

COCO annotation refers to image {image_name}, which produces an invalid path: {exc}

What it means

Raised by load_coco_annotations when Path(...).resolve() raises OSError or ValueError while resolving the joined image path. This is the wrapper around path resolution for the file_name field: the OS itself rejected the path (e.g. embedded null bytes) before any of the containment checks could run.

Source

Thrown at src/supervision/dataset/formats/coco.py:529

    images_directory_resolved = Path(images_directory_path).resolve()

    for coco_image in tqdm(
        coco_images,
        total=len(coco_images),
        desc="Loading COCO annotations",
        disable=not show_progress,
    ):
        image_name, image_width, image_height = (
            coco_image["file_name"],
            coco_image["width"],
            coco_image["height"],
        )
        image_annotations = coco_annotations_groups.get(coco_image["id"], [])
        image_path = str(Path(images_directory_path) / Path(image_name))
        try:
            resolved_image_path = Path(image_path).resolve()
        except (OSError, ValueError) as exc:
            raise ValueError(
                f"COCO annotation refers to image {image_name!r}, which "
                f"produces an invalid path: {exc}"
            ) from exc
        if resolved_image_path == images_directory_resolved:
            raise ValueError(
                f"COCO annotation refers to image {image_name!r}, which "
                f"resolves to the images directory itself "
                f"({images_directory_resolved}). Expected a path to an "
                "image file."
            )
        if images_directory_resolved not in resolved_image_path.parents:
            raise ValueError(
                f"COCO annotation refers to image {image_name!r}, which "
                f"resolves to {resolved_image_path} — outside the images "
                f"directory {images_directory_resolved}."
            )
        if resolved_image_path.is_dir():
            raise ValueError(

View on GitHub (pinned to 7f254d9784)

Solutions

  1. Sanitize file_name fields: strip NUL bytes and control characters (name.replace('\x00', '')).
  2. Locate the offending entry by printing each file_name with repr() before load; repr exposes hidden characters.
  3. Regenerate the JSON from the original source after fixing the writer.

Example fix

// before
{"file_name": "img\u0000.jpg", ...}

// after
{"file_name": "img.jpg", ...}
Defensive patterns

Strategy: validation

Validate before calling

import json
from pathlib import Path

def sanitize_coco_file_names(annotations_path: str) -> int:
    """Strip NUL/control characters from file_name; return count fixed."""
    data = json.loads(Path(annotations_path).read_text())
    fixed = 0
    for img in data["images"]:
        clean = "".join(ch for ch in img["file_name"] if ch.isprintable())
        if clean != img["file_name"]:
            img["file_name"], fixed = clean, fixed + 1
    Path(annotations_path).write_text(json.dumps(data))
    return fixed

Type guard

def is_resolvable_name(name: str) -> bool:
    """True when the string has no NUL bytes and can be an OS path component."""
    return isinstance(name, str) and "\x00" not in name and name == name.strip()

Try / catch

try:
    sv.DetectionDataset.from_coco(images_directory_path=d, annotations_path=a)
except ValueError as exc:
    if "invalid path" in str(exc):
        sanitize_coco_file_names(a)
    else:
        raise

Prevention

When it happens

Trigger: A COCO entry whose file_name contains characters that make it unresolvable — classically an embedded NUL byte ('\0') which raises ValueError in the OS path APIs, or OSError from pathological filesystem state.

Common situations: Binary corruption in annotation files; generation from bytes buffers where a NUL leaked into a string; extremely long path components on some platforms.

Related errors


AI-assisted analysis of roboflow/supervision@7f254d9784 (2026-08-15). Data as JSON: /api/errors/9f526191821e7ea3. Report an issue: GitHub.