roboflow/supervision · error · ValueError

COCO annotation refers to image {image_name}, which resolves

Error message

COCO annotation refers to image {image_name}, which resolves to the images directory itself ({images_directory_resolved}). Expected a path to an image file.

What it means

Raised by load_coco_annotations while resolving an image's file_name from the COCO JSON. After joining images_directory_path with the entry's file_name and calling Path.resolve(), the result equals the images directory itself, which means the annotation names no actual image file. This is part of supervision's path-traversal protection on COCO loading.

Source

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

        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(
                f"COCO annotation refers to image {image_name!r}, which "
                f"resolves to directory {resolved_image_path}. Expected a "
                "path to an image file."
            )
        image_path = str(resolved_image_path)

View on GitHub (pinned to 7f254d9784)

Solutions

  1. Inspect the images[].file_name entries in the annotations JSON and fix empty/'.' values to real relative filenames.
  2. Regenerate the COCO file with a correct exporter (e.g. supervision's save_coco_annotations).
  3. If the JSON is produced by your own code, assert file_name is a non-empty basename before writing.

Example fix

// before (JSON entry)
{"id": 1, "file_name": "", "width": 640, "height": 480}

// after
{"id": 1, "file_name": "000001.jpg", "width": 640, "height": 480}
Defensive patterns

Strategy: validation

Validate before calling

import json
from pathlib import Path

def validate_coco_file_names(annotations_path: str, images_dir: str) -> None:
    """Fail fast on file_name values that resolve to the images directory."""
    data = json.loads(Path(annotations_path).read_text())
    imgs_dir = Path(images_dir).resolve()
    for img in data.get("images", []):
        name = img.get("file_name", "")
        if not name or Path(imgs_dir, name).resolve() == imgs_dir:
            raise ValueError(f"Bad file_name {name!r} on image id {img.get('id')}")

Type guard

def is_valid_coco_file_name(name: object) -> bool:
    """True when file_name is a non-empty string naming a file, not a dir root."""
    return isinstance(name, str) and name.strip() not in ("", ".", "./") and not name.endswith("/")

Try / catch

try:
    ds = sv.DetectionDataset.from_coco(images_directory_path=d, annotations_path=a)
except ValueError as exc:
    if "images directory itself" in str(exc):
        raise ValueError(f"Malformed file_name in {a}; fix empty file_name entries") from exc
    raise

Prevention

When it happens

Trigger: A COCO JSON entry whose file_name is "", ".", or "./" — anything that resolves to the images directory root. load_coco_annotations(images_directory_path=..., annotations_path=...) hits this during its per-image loop.

Common situations: Hand-edited or machine-generated COCO files with empty file_name fields; a conversion script that writes os.path.dirname of a path into file_name; corrupted export from another tool.

Related errors


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