{"record":{"id":"e5b782254ffa0617","repo":"huggingface/transformers","slug":"incorrect-format-used-for-image-should-be-a-url","errorCode":null,"errorMessage":"Incorrect format used for image. Should be a URL, a local path, a base64 string, or a PIL image.","messagePattern":"Incorrect format used for image\\. Should be a URL, a local path, a base64 string, or a PIL image\\.","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"src/transformers/image_utils.py","lineNumber":556,"sourceCode":"            return decode_image(buf, mode=ImageReadMode.RGB)\n        elif os.path.isfile(image):\n            return decode_image(image, mode=ImageReadMode.RGB)\n        else:\n            if image.startswith(\"data:image/\"):\n                image = image.split(\",\")[1]\n            try:\n                raw = base64.decodebytes(image.encode())\n            except Exception as e:\n                raise ValueError(\n                    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}\"\n                )\n            buf = torch.frombuffer(bytearray(raw), dtype=torch.uint8)\n            return decode_image(buf, mode=ImageReadMode.RGB)\n    elif isinstance(image, PIL.Image.Image):\n        image = PIL.ImageOps.exif_transpose(image)\n        return pil_to_tensor(image.convert(\"RGB\"))\n    else:\n        raise TypeError(\n            \"Incorrect format used for image. Should be a URL, a local path, a base64 string, or a PIL image.\"\n        )\n\n\ndef load_images(\n    images: Union[list, tuple, str, \"PIL.Image.Image\"], timeout: float | None = None\n) -> Union[\"PIL.Image.Image\", list[\"PIL.Image.Image\"], list[list[\"PIL.Image.Image\"]]]:\n    \"\"\"Loads images, handling different levels of nesting.\n\n    Args:\n      images: A single image, a list of images, or a list of lists of images to load.\n      timeout: Timeout for loading images.\n\n    Returns:\n      A single image, a list of images, a list of lists of images.\n    \"\"\"\n    if isinstance(images, (list, tuple)):\n        if len(images) and isinstance(images[0], (list, tuple)):","sourceCodeStart":538,"sourceCodeEnd":574,"githubUrl":"https://github.com/huggingface/transformers/blob/a597f974857b3d92939971296bc0deb93d33d780/src/transformers/image_utils.py#L538-L574","documentation":"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.","triggerScenarios":"`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.","commonSituations":"Assuming the tensor-returning loader also converts existing arrays/tensors; feeding manually downloaded bytes; passing an unset variable from config-driven pipelines.","solutions":["For numpy/PIL inputs that need a tensor, use torchvision directly: `to_tensor(img)` or `torch.from_numpy(arr)`.","Keep `load_image_as_tensor` only for string sources (URL/path/base64) and PIL images.","For multiple images, iterate or use `load_images`."],"exampleFix":"// before\nt = load_image_as_tensor(np_img)  # TypeError\n\n// after\nimport torchvision.transforms.functional as F\nt = F.to_tensor(pil_img)          # PIL -> tensor\nt = torch.from_numpy(np_img)      # numpy -> tensor","handlingStrategy":"type-guard","validationCode":null,"typeGuard":"def is_load_image_as_tensor_input(x) -> bool:\n    import PIL\n    return isinstance(x, str) or isinstance(x, PIL.Image.Image)","tryCatchPattern":null,"preventionTips":["Use load_image_as_tensor only for string sources and PIL images.","Convert arrays/tensors with torchvision's to_tensor or torch.from_numpy instead.","Check torchvision is installed — the loader requires that backend."],"tags":["image-processing","type-checking","torch","loading"],"backgroundTag":null,"analyzedSha":"a597f974857b3d92939971296bc0deb93d33d780","analyzedAt":"2026-08-14T18:24:08.354Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}