Loads `image` to a PIL Image. Args: image (`str` or `PIL.Image.Image`): The image to convert to the PIL Image format. timeout (`float`, *optional*): The timeout value in seconds for the URL request. Returns: `PIL.Image.Image`: A PIL Imag
(image: Union[str, "PIL.Image.Image"], timeout: Optional[float] = None)
| 342 | |
| 343 | |
| 344 | def load_image(image: Union[str, "PIL.Image.Image"], timeout: Optional[float] = None) -> "PIL.Image.Image": |
| 345 | """ |
| 346 | Loads `image` to a PIL Image. |
| 347 | |
| 348 | Args: |
| 349 | image (`str` or `PIL.Image.Image`): |
| 350 | The image to convert to the PIL Image format. |
| 351 | timeout (`float`, *optional*): |
| 352 | The timeout value in seconds for the URL request. |
| 353 | |
| 354 | Returns: |
| 355 | `PIL.Image.Image`: A PIL Image. |
| 356 | """ |
| 357 | requires_backends(load_image, ["vision"]) |
| 358 | if isinstance(image, str): |
| 359 | if image.startswith("http://") or image.startswith("https://"): |
| 360 | # We need to actually check for a real protocol, otherwise it's impossible to use a local file |
| 361 | # like http_huggingface_co.png |
| 362 | image = PIL.Image.open(BytesIO(requests.get(image, timeout=timeout).content)) |
| 363 | elif os.path.isfile(image): |
| 364 | image = PIL.Image.open(image) |
| 365 | else: |
| 366 | if image.startswith("data:image/"): |
| 367 | image = image.split(",")[1] |
| 368 | |
| 369 | # Try to load as base64 |
| 370 | try: |
| 371 | b64 = base64.decodebytes(image.encode()) |
| 372 | image = PIL.Image.open(BytesIO(b64)) |
| 373 | except Exception as e: |
| 374 | raise ValueError( |
| 375 | 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}" |
| 376 | ) |
| 377 | elif isinstance(image, PIL.Image.Image): |
| 378 | image = image |
| 379 | else: |
| 380 | raise TypeError( |
| 381 | "Incorrect format used for image. Should be an url linking to an image, a base64 string, a local path, or a PIL image." |
| 382 | ) |
| 383 | image = PIL.ImageOps.exif_transpose(image) |
| 384 | image = image.convert("RGB") |
| 385 | return image |
| 386 | |
| 387 | |
| 388 | def validate_preprocess_arguments( |