File size: 1,602 Bytes
19b3da3
 
42ef134
19b3da3
 
 
 
 
 
 
 
 
8aeb9e5
19b3da3
 
8aeb9e5
19b3da3
8aeb9e5
19b3da3
a3d6c18
 
42ef134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3d6c18
 
 
 
 
 
 
 
 
 
 
049a85c
a3d6c18
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import io

import numpy as np
from PIL import Image


def to_bytes(image: Image.Image) -> bytes:
    with io.BytesIO() as output:
        image.save(output, format="JPEG")
        return output.getvalue()


def resize_image(image: Image.Image, dimension: int = 512) -> Image.Image:
    iw, ih = image.size
    if iw > ih:
        image = image.resize((dimension, int(dimension * ih / iw)))
    else:
        image = image.resize((int(dimension * iw / ih), dimension))
    return image


def HWC3(x):
    "x: numpy array"
    assert x.dtype == np.uint8
    if x.ndim == 2:
        x = x[:, :, None]
    assert x.ndim == 3
    H, W, C = x.shape
    assert C == 1 or C == 3 or C == 4
    if C == 3:
        return x
    if C == 1:
        return np.concatenate([x, x, x], axis=2)
    if C == 4:
        color = x[:, :, 0:3].astype(np.float32)
        alpha = x[:, :, 3:4].astype(np.float32) / 255.0
        y = color * alpha + 255.0 * (1.0 - alpha)
        y = y.clip(0, 255).astype(np.uint8)
        return y


def from_bytes(data: bytes) -> Image.Image:
    return Image.open(io.BytesIO(data))


def padd_image(image: Image.Image, to_width: int, to_height: int) -> Image.Image:
    iw, ih = image.size

    value = min(to_width, to_height)
    # resize Image
    if iw > ih:
        image = image.resize((value, int(value * ih / iw)))
    elif ih > iw:
        image = image.resize((int(value * iw / ih), value))

    # padd Image
    iw, ih = image.size
    img = Image.new("RGBA", (to_width, to_height), (0, 0, 0, 0))
    img.paste(image, ((to_width - iw) // 2, (to_height - ih) // 2))
    return img