huggingface/transformers · error · TypeError

Incorrect format used for image. Should be a URL, a local pa

Error message

Incorrect format used for image. Should be a URL, a local path, a base64 string, or a PIL image.

What it means

Raised as TypeError by `transformers.image_utils.load_image_as_tensor` when the input is neither a string nor a PIL.Image.Image. This torchvision-backed loader (decorated `@requires(backends=("torchvision",))`) accepts only URL/path/base64 strings and PIL images; numpy arrays, torch tensors, bytes, lists, and None are rejected.

Source

Thrown at src/transformers/image_utils.py:556

            return decode_image(buf, mode=ImageReadMode.RGB)
        elif os.path.isfile(image):
            return decode_image(image, mode=ImageReadMode.RGB)
        else:
            if image.startswith("data:image/"):
                image = image.split(",")[1]
            try:
                raw = base64.decodebytes(image.encode())
            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}"
                )
            buf = torch.frombuffer(bytearray(raw), dtype=torch.uint8)
            return decode_image(buf, mode=ImageReadMode.RGB)
    elif isinstance(image, PIL.Image.Image):
        image = PIL.ImageOps.exif_transpose(image)
        return pil_to_tensor(image.convert("RGB"))
    else:
        raise TypeError(
            "Incorrect format used for image. Should be a URL, a local path, a base64 string, or a PIL image."
        )


def load_images(
    images: Union[list, tuple, str, "PIL.Image.Image"], timeout: float | None = None
) -> Union["PIL.Image.Image", list["PIL.Image.Image"], list[list["PIL.Image.Image"]]]:
    """Loads images, handling different levels of nesting.

    Args:
      images: A single image, a list of images, or a list of lists of images to load.
      timeout: Timeout for loading images.

    Returns:
      A single image, a list of images, a list of lists of images.
    """
    if isinstance(images, (list, tuple)):
        if len(images) and isinstance(images[0], (list, tuple)):

View on GitHub (pinned to a597f97485)

Solutions

  1. For numpy/PIL inputs that need a tensor, use torchvision directly: `to_tensor(img)` or `torch.from_numpy(arr)`.
  2. Keep `load_image_as_tensor` only for string sources (URL/path/base64) and PIL images.
  3. For multiple images, iterate or use `load_images`.

Example fix

// before
t = load_image_as_tensor(np_img)  # TypeError

// after
import torchvision.transforms.functional as F
t = F.to_tensor(pil_img)          # PIL -> tensor
t = torch.from_numpy(np_img)      # numpy -> tensor
Defensive patterns

Strategy: type-guard

Type guard

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

Prevention

When it happens

Trigger: `load_image_as_tensor(np_array)`, `load_image_as_tensor(torch_tensor)`, `load_image_as_tensor(b'\x89PNG...')`, or `load_image_as_tensor(None)`. Lists of sources must go through `load_images` or a loop.

Common situations: Assuming the tensor-returning loader also converts existing arrays/tensors; feeding manually downloaded bytes; passing an unset variable from config-driven pipelines.

Related errors


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