visual.py 1.5 KB
Newer Older
L
LielinJiang 已提交
1 2 3 4
import numpy as np
from PIL import Image


L
LielinJiang 已提交
5
def tensor2img(input_image, min_max=(-1., 1.), imtype=np.uint8):
L
LielinJiang 已提交
6 7 8 9 10 11 12 13 14 15 16 17
    """"Converts a Tensor array into a numpy image array.

    Parameters:
        input_image (tensor) --  the input image tensor array
        imtype (type)        --  the desired type of the converted numpy array
    """
    if not isinstance(input_image, np.ndarray):
        image_numpy = input_image.numpy()  # convert it into a numpy array
        if len(image_numpy.shape) == 4:
            image_numpy = image_numpy[0]
        if image_numpy.shape[0] == 1:  # grayscale to RGB
            image_numpy = np.tile(image_numpy, (3, 1, 1))
L
LielinJiang 已提交
18 19
        image_numpy = image_numpy.clip(min_max[0], min_max[1])
        image_numpy = (image_numpy - min_max[0]) / (min_max[1] - min_max[0])
L
LielinJiang 已提交
20
        image_numpy = (np.transpose(image_numpy, (1, 2, 0))) * 255.0  # post-processing: tranpose and scaling
L
LielinJiang 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
    else:  # if it is a numpy array, do nothing
        image_numpy = input_image
    return image_numpy.astype(imtype)


def save_image(image_numpy, image_path, aspect_ratio=1.0):
    """Save a numpy image to the disk

    Parameters:
        image_numpy (numpy array) -- input numpy array
        image_path (str)          -- the path of the image
    """

    image_pil = Image.fromarray(image_numpy)
    h, w, _ = image_numpy.shape

    if aspect_ratio > 1.0:
        image_pil = image_pil.resize((h, int(w * aspect_ratio)), Image.BICUBIC)
    if aspect_ratio < 1.0:
        image_pil = image_pil.resize((int(h / aspect_ratio), w), Image.BICUBIC)
    image_pil.save(image_path)