huggingface/transformers · error · TypeError

Incorrect format used for image. Should be an url linking to

Error message

Incorrect format used for image. Should be an url linking to an image, a base64 string, a local path, or a PIL image.

What it means

Raised as TypeError by `transformers.image_utils.load_image` when the input is not a string and not a PIL.Image.Image — i.e. the else-branch of the type dispatch. `load_image` accepts exactly three things: URL/path/base64 strings, and PIL images. Numpy arrays, torch tensors, bytes, and None are all rejected with this message.

Source

Thrown at src/transformers/image_utils.py:507

            # 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.

    Args:
        image (`str` or `PIL.Image.Image`):
            The image to convert to the PIL Image format.

View on GitHub (pinned to a597f97485)

Solutions

  1. For numpy/torch inputs, skip loading — they are already valid image inputs for processors.
  2. Wrap raw bytes: `PIL.Image.open(BytesIO(raw))`.
  3. For lists of images, call `load_images(...)` instead.
  4. Ensure upstream fetches cannot pass None silently.

Example fix

// before
img = load_image(np.array(pil_img))   # TypeError

// after
img = pil_img                          # pass PIL directly to load_image, or:
inputs = processor(images=np.array(pil_img), return_tensors="pt")
Defensive patterns

Strategy: type-guard

Type guard

def is_load_image_input(x) -> bool:
    import PIL
    return isinstance(x, str) or isinstance(x, PIL.Image.Image)

Prevention

When it happens

Trigger: `load_image(np_array)`, `load_image(torch_tensor)`, `load_image(raw_bytes)`, or `load_image(None)` (e.g. from a failed fetch upstream). List inputs are also rejected here — use `load_images` for those.

Common situations: Assuming load_image is a universal converter and feeding it already-decoded arrays; bytes downloaded manually before calling; reusing the same variable for paths and loaded images in mixed pipelines.

Related errors


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