utils.py 7.61 KB
Newer Older
1
from typing import Union, Optional, List, Tuple, Text, BinaryIO
2
import pathlib
3
4
import torch
import math
5
6
7
8
9
10
import numpy as np
from PIL import Image, ImageDraw
from PIL import ImageFont

__all__ = ["make_grid", "save_image", "draw_bounding_boxes"]

11
irange = range
12

13

14
def make_grid(
15
    tensor: Union[torch.Tensor, List[torch.Tensor]],
16
17
18
19
20
21
22
    nrow: int = 8,
    padding: int = 2,
    normalize: bool = False,
    range: Optional[Tuple[int, int]] = None,
    scale_each: bool = False,
    pad_value: int = 0,
) -> torch.Tensor:
23
    """Make a grid of images.
24

25
26
27
    Args:
        tensor (Tensor or list): 4D mini-batch Tensor of shape (B x C x H x W)
            or a list of images all of the same size.
28
        nrow (int, optional): Number of images displayed in each row of the grid.
Tongzhou Wang's avatar
Tongzhou Wang committed
29
30
            The final grid size is ``(B / nrow, nrow)``. Default: ``8``.
        padding (int, optional): amount of padding. Default: ``2``.
31
        normalize (bool, optional): If True, shift the image to the range (0, 1),
Tongzhou Wang's avatar
Tongzhou Wang committed
32
            by the min and max values specified by :attr:`range`. Default: ``False``.
33
34
35
        range (tuple, optional): tuple (min, max) where min and max are numbers,
            then these numbers are used to normalize the image. By default, min and max
            are computed from the tensor.
Tongzhou Wang's avatar
Tongzhou Wang committed
36
37
38
        scale_each (bool, optional): If ``True``, scale each image in the batch of
            images separately rather than the (min, max) over all images. Default: ``False``.
        pad_value (float, optional): Value for the padded pixels. Default: ``0``.
39

40
41
    Example:
        See this notebook `here <https://gist.github.com/anonymous/bf16430f7750c023141c562f3e9f2a91>`_
42

43
    """
44
45
46
47
    if not (torch.is_tensor(tensor) or
            (isinstance(tensor, list) and all(torch.is_tensor(t) for t in tensor))):
        raise TypeError('tensor or list of tensors expected, got {}'.format(type(tensor)))

48
    # if list of tensors, convert to a 4D mini-batch Tensor
49
    if isinstance(tensor, list):
50
        tensor = torch.stack(tensor, dim=0)
51

52
    if tensor.dim() == 2:  # single image H x W
53
        tensor = tensor.unsqueeze(0)
54
    if tensor.dim() == 3:  # single image
55
        if tensor.size(0) == 1:  # if single-channel, convert to 3-channel
Adam Lerer's avatar
Adam Lerer committed
56
            tensor = torch.cat((tensor, tensor, tensor), 0)
57
        tensor = tensor.unsqueeze(0)
58

59
    if tensor.dim() == 4 and tensor.size(1) == 1:  # single-channel images
60
        tensor = torch.cat((tensor, tensor, tensor), 1)
61
62

    if normalize is True:
63
        tensor = tensor.clone()  # avoid modifying tensor in-place
64
65
66
67
        if range is not None:
            assert isinstance(range, tuple), \
                "range has to be a tuple (min, max) if specified. min and max are numbers"

68
69
70
        def norm_ip(img, low, high):
            img.clamp_(min=low, max=high)
            img.sub_(low).div_(max(high - low, 1e-5))
71
72
73
74
75

        def norm_range(t, range):
            if range is not None:
                norm_ip(t, range[0], range[1])
            else:
76
                norm_ip(t, float(t.min()), float(t.max()))
77
78
79
80
81
82
83

        if scale_each is True:
            for t in tensor:  # loop over mini-batch dimension
                norm_range(t, range)
        else:
            norm_range(tensor, range)

84
    if tensor.size(0) == 1:
85
        return tensor.squeeze(0)
86

87
88
89
    # make the mini-batch of images into a grid
    nmaps = tensor.size(0)
    xmaps = min(nrow, nmaps)
90
    ymaps = int(math.ceil(float(nmaps) / xmaps))
91
    height, width = int(tensor.size(2) + padding), int(tensor.size(3) + padding)
92
93
    num_channels = tensor.size(1)
    grid = tensor.new_full((num_channels, height * ymaps + padding, width * xmaps + padding), pad_value)
94
    k = 0
95
96
    for y in irange(ymaps):
        for x in irange(xmaps):
97
98
            if k >= nmaps:
                break
99
100
101
102
103
            # Tensor.copy_() is a valid method but seems to be missing from the stubs
            # https://pytorch.org/docs/stable/tensors.html#torch.Tensor.copy_
            grid.narrow(1, y * height + padding, height - padding).narrow(  # type: ignore[attr-defined]
                2, x * width + padding, width - padding
            ).copy_(tensor[k])
104
105
106
107
            k = k + 1
    return grid


108
def save_image(
109
    tensor: Union[torch.Tensor, List[torch.Tensor]],
110
111
112
113
114
115
116
117
118
    fp: Union[Text, pathlib.Path, BinaryIO],
    nrow: int = 8,
    padding: int = 2,
    normalize: bool = False,
    range: Optional[Tuple[int, int]] = None,
    scale_each: bool = False,
    pad_value: int = 0,
    format: Optional[str] = None,
) -> None:
119
120
121
122
123
    """Save a given Tensor into an image file.

    Args:
        tensor (Tensor or list): Image to be saved. If given a mini-batch tensor,
            saves the tensor as a grid of images by calling ``make_grid``.
124
        fp (string or file object): A filename or a file object
125
126
        format(Optional):  If omitted, the format to use is determined from the filename extension.
            If a file object was used instead of a filename, this parameter should always be used.
127
        **kwargs: Other arguments are documented in ``make_grid``.
128
    """
129
    grid = make_grid(tensor, nrow=nrow, padding=padding, pad_value=pad_value,
130
                     normalize=normalize, range=range, scale_each=scale_each)
131
    # Add 0.5 after unnormalizing to [0, 255] to round to nearest integer
132
    ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to('cpu', torch.uint8).numpy()
133
    im = Image.fromarray(ndarr)
134
    im.save(fp, format=format)
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179


@torch.no_grad()
def draw_bounding_boxes(
    image: torch.Tensor,
    boxes: torch.Tensor,
    labels: Optional[List[str]] = None,
    colors: Optional[List[Union[str, Tuple[int, int, int]]]] = None,
    width: int = 1,
    font: Optional[str] = None,
    font_size: int = 10
) -> torch.Tensor:

    """
    Draws bounding boxes on given image.
    The values of the input image should be uint8 between 0 and 255.

    Args:
        image (Tensor): Tensor of shape (C x H x W)
        bboxes (Tensor): Tensor of size (N, 4) containing bounding boxes in (xmin, ymin, xmax, ymax) format. Note that
            the boxes are absolute coordinates with respect to the image. In other words: `0 <= xmin < xmax < W` and
            `0 <= ymin < ymax < H`.
        labels (List[str]): List containing the labels of bounding boxes.
        colors (List[Union[str, Tuple[int, int, int]]]): List containing the colors of bounding boxes. The colors can
            be represented as `str` or `Tuple[int, int, int]`.
        width (int): Width of bounding box.
        font (str): A filename containing a TrueType font. If the file is not found in this filename, the loader may
            also search in other directories, such as the `fonts/` directory on Windows or `/Library/Fonts/`,
            `/System/Library/Fonts/` and `~/Library/Fonts/` on macOS.
        font_size (int): The requested font size in points.
    """

    if not isinstance(image, torch.Tensor):
        raise TypeError(f"Tensor expected, got {type(image)}")
    elif image.dtype != torch.uint8:
        raise ValueError(f"Tensor uint8 expected, got {image.dtype}")
    elif image.dim() != 3:
        raise ValueError("Pass individual images, not batches")

    ndarr = image.permute(1, 2, 0).numpy()
    img_to_draw = Image.fromarray(ndarr)

    img_boxes = boxes.to(torch.int64).tolist()

    draw = ImageDraw.Draw(img_to_draw)
180
    txt_font = ImageFont.load_default() if font is None else ImageFont.truetype(font=font, size=font_size)
181
182
183
184
185
186
187
188
189

    for i, bbox in enumerate(img_boxes):
        color = None if colors is None else colors[i]
        draw.rectangle(bbox, width=width, outline=color)

        if labels is not None:
            draw.text((bbox[0], bbox[1]), labels[i], fill=color, font=txt_font)

    return torch.from_numpy(np.array(img_to_draw)).permute(2, 0, 1)