pil_utils.py 1.39 KB
Newer Older
1
2
3
import PIL.Image
import PIL.ImageOps
from packaging import version
Patrick von Platen's avatar
Patrick von Platen committed
4
from PIL import Image
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22


if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
    PIL_INTERPOLATION = {
        "linear": PIL.Image.Resampling.BILINEAR,
        "bilinear": PIL.Image.Resampling.BILINEAR,
        "bicubic": PIL.Image.Resampling.BICUBIC,
        "lanczos": PIL.Image.Resampling.LANCZOS,
        "nearest": PIL.Image.Resampling.NEAREST,
    }
else:
    PIL_INTERPOLATION = {
        "linear": PIL.Image.LINEAR,
        "bilinear": PIL.Image.BILINEAR,
        "bicubic": PIL.Image.BICUBIC,
        "lanczos": PIL.Image.LANCZOS,
        "nearest": PIL.Image.NEAREST,
    }
Patrick von Platen's avatar
Patrick von Platen committed
23
24
25


def pt_to_pil(images):
Steven Liu's avatar
Steven Liu committed
26
27
28
    """
    Convert a torch image to a PIL image.
    """
Patrick von Platen's avatar
Patrick von Platen committed
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
    images = (images / 2 + 0.5).clamp(0, 1)
    images = images.cpu().permute(0, 2, 3, 1).float().numpy()
    images = numpy_to_pil(images)
    return images


def numpy_to_pil(images):
    """
    Convert a numpy image or a batch of images to a PIL image.
    """
    if images.ndim == 3:
        images = images[None, ...]
    images = (images * 255).round().astype("uint8")
    if images.shape[-1] == 1:
        # special case for grayscale (single channel) images
        pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
    else:
        pil_images = [Image.fromarray(image) for image in images]

    return pil_images