loading_utils.py 1.51 KB
Newer Older
Dhruv Nair's avatar
Dhruv Nair committed
1
import os
2
from typing import Callable, Union
Dhruv Nair's avatar
Dhruv Nair committed
3
4
5
6
7
8

import PIL.Image
import PIL.ImageOps
import requests


9
10
11
def load_image(
    image: Union[str, PIL.Image.Image], convert_method: Callable[[PIL.Image.Image], PIL.Image.Image] = None
) -> PIL.Image.Image:
Dhruv Nair's avatar
Dhruv Nair committed
12
13
14
15
16
17
    """
    Loads `image` to a PIL Image.

    Args:
        image (`str` or `PIL.Image.Image`):
            The image to convert to the PIL Image format.
18
        convert_method (Callable[[PIL.Image.Image], PIL.Image.Image], optional):
19
20
            A conversion method to apply to the image after loading it. When set to `None` the image will be converted
            "RGB".
21

Dhruv Nair's avatar
Dhruv Nair committed
22
23
24
25
26
27
28
29
30
31
32
    Returns:
        `PIL.Image.Image`:
            A PIL Image.
    """
    if isinstance(image, str):
        if image.startswith("http://") or image.startswith("https://"):
            image = PIL.Image.open(requests.get(image, stream=True).raw)
        elif os.path.isfile(image):
            image = PIL.Image.open(image)
        else:
            raise ValueError(
33
                f"Incorrect path or URL. URLs must start with `http://` or `https://`, and {image} is not a valid path."
Dhruv Nair's avatar
Dhruv Nair committed
34
            )
35
36
    elif isinstance(image, PIL.Image.Image):
        image = image
Dhruv Nair's avatar
Dhruv Nair committed
37
38
    else:
        raise ValueError(
39
            "Incorrect format used for the image. Should be a URL linking to an image, a local path, or a PIL image."
Dhruv Nair's avatar
Dhruv Nair committed
40
        )
41

Dhruv Nair's avatar
Dhruv Nair committed
42
    image = PIL.ImageOps.exif_transpose(image)
43
44
45
46
47
48

    if convert_method is not None:
        image = convert_method(image)
    else:
        image = image.convert("RGB")

Dhruv Nair's avatar
Dhruv Nair committed
49
    return image