huggingface/transformers · error · ValueError

Incorrect image source. Must be a valid URL starting with `h

Error message

Incorrect image source. Must be a valid URL starting with `http://` or `https://`, a valid path to an image file, or a base64 encoded string. Got {image}. Failed with {e}

What it means

Raised by `transformers.image_utils.load_image` when a string input is neither an http(s) URL (that branch fetches directly), nor an existing file path (os.path.isfile), and the final fallback — decoding it as base64 and opening it with PIL — throws. The caught exception `e` is appended, revealing the real cause (usually a binascii base64 error or PIL 'cannot identify image file'). The string was probably meant to be a path that doesn't exist or a malformed base64 payload.

Source

Thrown at src/transformers/image_utils.py:503

    """
    requires_backends(load_image, ["vision"])
    if isinstance(image, str):
        if image.startswith("http://") or image.startswith("https://"):
            # We need to actually check for a real protocol, otherwise it's impossible to use a local file
            # like http_huggingface_co.png
            image = PIL.Image.open(BytesIO(httpx.get(image, timeout=timeout, follow_redirects=True).content))
        elif os.path.isfile(image):
            image = PIL.Image.open(image)
        else:
            if image.startswith("data:image/"):
                image = image.split(",")[1]

            # Try to load as base64
            try:
                b64 = base64.decodebytes(image.encode())
                image = PIL.Image.open(BytesIO(b64))
            except Exception as e:
                raise ValueError(
                    f"Incorrect image source. Must be a valid URL starting with `http://` or `https://`, a valid path to an image file, or a base64 encoded string. Got {image}. Failed with {e}"
                )
    elif not isinstance(image, PIL.Image.Image):
        raise TypeError(
            "Incorrect format used for image. Should be an url linking to an image, a base64 string, a local path, or a PIL image."
        )
    image = PIL.ImageOps.exif_transpose(image)
    image = image.convert("RGB")
    return image


@requires(backends=("torchvision",))
def load_image_as_tensor(
    image: Union[str, "PIL.Image.Image"],
    timeout: float | None = None,
) -> "torch.Tensor":
    """
    Loads `image` directly to a `torch.Tensor` using torchvision.

View on GitHub (pinned to a597f97485)

Solutions

  1. Verify the path exists first: `os.path.isfile(path)`; check cwd if using relative paths.
  2. For base64, ensure it is pure base64 (strip the 'data:image/...;base64,' prefix is handled, but remove whitespace/newlines) and that the bytes decode to a real image.
  3. For URLs, confirm the scheme is http:// or https:// — scheme-less URLs fall into the file/base64 branches.
  4. Inspect the appended `Failed with {e}` to see whether base64 decoding or PIL opening failed.

Example fix

// before
img = load_image("./images/cat.jpg")   # cwd changed -> not a file -> base64 fail

// after
import os
path = os.path.abspath("images/cat.jpg")
assert os.path.isfile(path), path
img = load_image(path)
// base64 case:
b64 = "".join(b64.split())             # strip whitespace
img = load_image(b64)
Defensive patterns

Strategy: try-catch

Validate before calling

import os

def is_loadable_source(s: str) -> bool:
    return s.startswith(("http://", "https://")) or os.path.isfile(s) or s.startswith("data:image/")

assert is_loadable_source(path_or_url), f"not a URL, existing file, or data URI: {path_or_url}"

Try / catch

from transformers.image_utils import load_image

try:
    img = load_image(src, timeout=10)
except ValueError as e:
    # retry once (e.g. transient FS sync), then fall back to another source
    try:
        img = load_image(fallback_src)
    except ValueError:
        raise RuntimeError(f"could not load image source: {src}") from e

Prevention

When it happens

Trigger: `load_image('/data/missing.jpg')` (typo'd or moved file); a relative path evaluated from the wrong working directory; a base64 string with whitespace/newlines or a broken 'data:image/...;base64,' prefix split; a corrupt/empty downloaded payload; a URL missing the scheme (treated as path, then base64).

Common situations: Datasets that moved or weren't downloaded; notebooks run from a different cwd so relative paths break; base64 copied from JSON with escaped characters; files with wrong extension or truncated transfers.

Related errors


AI-assisted analysis of huggingface/transformers@a597f97485 (2026-08-14). Data as JSON: /api/errors/5bd68023ce40ecb6. Report an issue: GitHub.