image_processor.py 13 KB
Newer Older
YiYi Xu's avatar
YiYi Xu committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import warnings
16
from typing import List, Optional, Union
YiYi Xu's avatar
YiYi Xu committed
17
18
19
20
21
22
23

import numpy as np
import PIL
import torch
from PIL import Image

from .configuration_utils import ConfigMixin, register_to_config
24
from .utils import CONFIG_NAME, PIL_INTERPOLATION, deprecate
YiYi Xu's avatar
YiYi Xu committed
25
26
27
28


class VaeImageProcessor(ConfigMixin):
    """
Steven Liu's avatar
Steven Liu committed
29
    Image processor for VAE.
YiYi Xu's avatar
YiYi Xu committed
30
31
32

    Args:
        do_resize (`bool`, *optional*, defaults to `True`):
33
            Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`. Can accept
Steven Liu's avatar
Steven Liu committed
34
            `height` and `width` arguments from [`image_processor.VaeImageProcessor.preprocess`] method.
YiYi Xu's avatar
YiYi Xu committed
35
        vae_scale_factor (`int`, *optional*, defaults to `8`):
Steven Liu's avatar
Steven Liu committed
36
            VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
YiYi Xu's avatar
YiYi Xu committed
37
38
39
        resample (`str`, *optional*, defaults to `lanczos`):
            Resampling filter to use when resizing the image.
        do_normalize (`bool`, *optional*, defaults to `True`):
Steven Liu's avatar
Steven Liu committed
40
            Whether to normalize the image to [-1,1].
41
42
        do_convert_rgb (`bool`, *optional*, defaults to be `False`):
            Whether to convert the images to RGB format.
YiYi Xu's avatar
YiYi Xu committed
43
44
45
46
47
48
49
50
51
52
53
    """

    config_name = CONFIG_NAME

    @register_to_config
    def __init__(
        self,
        do_resize: bool = True,
        vae_scale_factor: int = 8,
        resample: str = "lanczos",
        do_normalize: bool = True,
54
        do_convert_rgb: bool = False,
YiYi Xu's avatar
YiYi Xu committed
55
56
57
58
    ):
        super().__init__()

    @staticmethod
59
    def numpy_to_pil(images: np.ndarray) -> PIL.Image.Image:
YiYi Xu's avatar
YiYi Xu committed
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
        """
        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

    @staticmethod
75
76
    def pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
        """
Steven Liu's avatar
Steven Liu committed
77
        Convert a PIL image or a list of PIL images to NumPy arrays.
78
79
80
81
82
83
84
85
86
87
        """
        if not isinstance(images, list):
            images = [images]
        images = [np.array(image).astype(np.float32) / 255.0 for image in images]
        images = np.stack(images, axis=0)

        return images

    @staticmethod
    def numpy_to_pt(images: np.ndarray) -> torch.FloatTensor:
YiYi Xu's avatar
YiYi Xu committed
88
        """
Steven Liu's avatar
Steven Liu committed
89
        Convert a NumPy image to a PyTorch tensor.
YiYi Xu's avatar
YiYi Xu committed
90
91
92
93
94
95
96
97
        """
        if images.ndim == 3:
            images = images[..., None]

        images = torch.from_numpy(images.transpose(0, 3, 1, 2))
        return images

    @staticmethod
98
    def pt_to_numpy(images: torch.FloatTensor) -> np.ndarray:
YiYi Xu's avatar
YiYi Xu committed
99
        """
Steven Liu's avatar
Steven Liu committed
100
        Convert a PyTorch tensor to a NumPy image.
YiYi Xu's avatar
YiYi Xu committed
101
102
103
104
105
106
107
        """
        images = images.cpu().permute(0, 2, 3, 1).float().numpy()
        return images

    @staticmethod
    def normalize(images):
        """
Steven Liu's avatar
Steven Liu committed
108
        Normalize an image array to [-1,1].
YiYi Xu's avatar
YiYi Xu committed
109
110
111
        """
        return 2.0 * images - 1.0

112
113
114
    @staticmethod
    def denormalize(images):
        """
Steven Liu's avatar
Steven Liu committed
115
        Denormalize an image array to [0,1].
116
117
118
        """
        return (images / 2 + 0.5).clamp(0, 1)

119
120
121
122
123
124
125
126
127
128
129
130
131
132
    @staticmethod
    def convert_to_rgb(image: PIL.Image.Image) -> PIL.Image.Image:
        """
        Converts an image to RGB format.
        """
        image = image.convert("RGB")
        return image

    def resize(
        self,
        image: PIL.Image.Image,
        height: Optional[int] = None,
        width: Optional[int] = None,
    ) -> PIL.Image.Image:
YiYi Xu's avatar
YiYi Xu committed
133
        """
Steven Liu's avatar
Steven Liu committed
134
        Resize a PIL image. Both height and width are downscaled to the next integer multiple of `vae_scale_factor`.
YiYi Xu's avatar
YiYi Xu committed
135
        """
136
137
138
139
140
141
142
143
144
145
        if height is None:
            height = image.height
        if width is None:
            width = image.width

        width, height = (
            x - x % self.config.vae_scale_factor for x in (width, height)
        )  # resize to integer multiple of vae_scale_factor
        image = image.resize((width, height), resample=PIL_INTERPOLATION[self.config.resample])
        return image
YiYi Xu's avatar
YiYi Xu committed
146
147
148
149

    def preprocess(
        self,
        image: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
150
151
        height: Optional[int] = None,
        width: Optional[int] = None,
YiYi Xu's avatar
YiYi Xu committed
152
153
    ) -> torch.Tensor:
        """
Steven Liu's avatar
Steven Liu committed
154
        Preprocess the image input. Accepted formats are PIL images, NumPy arrays or PyTorch tensors.
YiYi Xu's avatar
YiYi Xu committed
155
156
157
158
159
160
161
162
163
164
        """
        supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
        if isinstance(image, supported_formats):
            image = [image]
        elif not (isinstance(image, list) and all(isinstance(i, supported_formats) for i in image)):
            raise ValueError(
                f"Input is in incorrect format: {[type(i) for i in image]}. Currently, we only support {', '.join(supported_formats)}"
            )

        if isinstance(image[0], PIL.Image.Image):
165
166
            if self.config.do_convert_rgb:
                image = [self.convert_to_rgb(i) for i in image]
167
            if self.config.do_resize:
168
169
                image = [self.resize(i, height, width) for i in image]
            image = self.pil_to_numpy(image)  # to np
YiYi Xu's avatar
YiYi Xu committed
170
171
172
173
174
175
            image = self.numpy_to_pt(image)  # to pt

        elif isinstance(image[0], np.ndarray):
            image = np.concatenate(image, axis=0) if image[0].ndim == 4 else np.stack(image, axis=0)
            image = self.numpy_to_pt(image)
            _, _, height, width = image.shape
176
177
178
            if self.config.do_resize and (
                height % self.config.vae_scale_factor != 0 or width % self.config.vae_scale_factor != 0
            ):
YiYi Xu's avatar
YiYi Xu committed
179
                raise ValueError(
180
                    f"Currently we only support resizing for PIL image - please resize your numpy array to be divisible by {self.config.vae_scale_factor}"
YiYi Xu's avatar
YiYi Xu committed
181
182
183
184
185
                    f"currently the sizes are {height} and {width}. You can also pass a PIL image instead to use resize option in VAEImageProcessor"
                )

        elif isinstance(image[0], torch.Tensor):
            image = torch.cat(image, axis=0) if image[0].ndim == 4 else torch.stack(image, axis=0)
186
187
188
189
190
191
            _, channel, height, width = image.shape

            # don't need any preprocess if the image is latents
            if channel == 4:
                return image

192
193
194
            if self.config.do_resize and (
                height % self.config.vae_scale_factor != 0 or width % self.config.vae_scale_factor != 0
            ):
YiYi Xu's avatar
YiYi Xu committed
195
                raise ValueError(
196
                    f"Currently we only support resizing for PIL image - please resize your pytorch tensor to be divisible by {self.config.vae_scale_factor}"
YiYi Xu's avatar
YiYi Xu committed
197
198
199
200
                    f"currently the sizes are {height} and {width}. You can also pass a PIL image instead to use resize option in VAEImageProcessor"
                )

        # expected range [0,1], normalize to [-1,1]
201
        do_normalize = self.config.do_normalize
YiYi Xu's avatar
YiYi Xu committed
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
        if image.min() < 0:
            warnings.warn(
                "Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] "
                f"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{image.min()},{image.max()}]",
                FutureWarning,
            )
            do_normalize = False

        if do_normalize:
            image = self.normalize(image)

        return image

    def postprocess(
        self,
217
        image: torch.FloatTensor,
YiYi Xu's avatar
YiYi Xu committed
218
        output_type: str = "pil",
219
        do_denormalize: Optional[List[bool]] = None,
YiYi Xu's avatar
YiYi Xu committed
220
    ):
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
        if not isinstance(image, torch.Tensor):
            raise ValueError(
                f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
            )
        if output_type not in ["latent", "pt", "np", "pil"]:
            deprecation_message = (
                f"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
                "`pil`, `np`, `pt`, `latent`"
            )
            deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
            output_type = "np"

        if output_type == "latent":
            return image

        if do_denormalize is None:
            do_denormalize = [self.config.do_normalize] * image.shape[0]

        image = torch.stack(
            [self.denormalize(image[i]) if do_denormalize[i] else image[i] for i in range(image.shape[0])]
        )

        if output_type == "pt":
YiYi Xu's avatar
YiYi Xu committed
244
245
246
247
248
249
            return image

        image = self.pt_to_numpy(image)

        if output_type == "np":
            return image
250
251

        if output_type == "pil":
YiYi Xu's avatar
YiYi Xu committed
252
            return self.numpy_to_pil(image)
estelleafl's avatar
estelleafl committed
253
254
255
256


class VaeImageProcessorLDM3D(VaeImageProcessor):
    """
Steven Liu's avatar
Steven Liu committed
257
    Image processor for VAE LDM3D.
estelleafl's avatar
estelleafl committed
258
259
260
261
262

    Args:
        do_resize (`bool`, *optional*, defaults to `True`):
            Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
        vae_scale_factor (`int`, *optional*, defaults to `8`):
Steven Liu's avatar
Steven Liu committed
263
            VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
estelleafl's avatar
estelleafl committed
264
265
266
        resample (`str`, *optional*, defaults to `lanczos`):
            Resampling filter to use when resizing the image.
        do_normalize (`bool`, *optional*, defaults to `True`):
Steven Liu's avatar
Steven Liu committed
267
            Whether to normalize the image to [-1,1].
estelleafl's avatar
estelleafl committed
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
    """

    config_name = CONFIG_NAME

    @register_to_config
    def __init__(
        self,
        do_resize: bool = True,
        vae_scale_factor: int = 8,
        resample: str = "lanczos",
        do_normalize: bool = True,
    ):
        super().__init__()

    @staticmethod
    def numpy_to_pil(images):
        """
Steven Liu's avatar
Steven Liu committed
285
        Convert a NumPy image or a batch of images to a PIL image.
estelleafl's avatar
estelleafl committed
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
        """
        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[:, :, :3]) for image in images]

        return pil_images

    @staticmethod
    def rgblike_to_depthmap(image):
        """
        Args:
            image: RGB-like depth image

        Returns: depth map

        """
        return image[:, :, 1] * 2**8 + image[:, :, 2]

    def numpy_to_depth(self, images):
        """
Steven Liu's avatar
Steven Liu committed
311
        Convert a NumPy depth image or a batch of images to a PIL image.
estelleafl's avatar
estelleafl committed
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
        """
        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
            raise Exception("Not supported")
        else:
            pil_images = [Image.fromarray(self.rgblike_to_depthmap(image[:, :, 3:]), mode="I;16") for image in images]

        return pil_images

    def postprocess(
        self,
        image: torch.FloatTensor,
        output_type: str = "pil",
        do_denormalize: Optional[List[bool]] = None,
    ):
        if not isinstance(image, torch.Tensor):
            raise ValueError(
                f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
            )
        if output_type not in ["latent", "pt", "np", "pil"]:
            deprecation_message = (
                f"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
                "`pil`, `np`, `pt`, `latent`"
            )
            deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
            output_type = "np"

        if do_denormalize is None:
            do_denormalize = [self.config.do_normalize] * image.shape[0]

        image = torch.stack(
            [self.denormalize(image[i]) if do_denormalize[i] else image[i] for i in range(image.shape[0])]
        )

        image = self.pt_to_numpy(image)

        if output_type == "np":
            return image[:, :, :, :3], np.stack([self.rgblike_to_depthmap(im[:, :, 3:]) for im in image], axis=0)

        if output_type == "pil":
            return self.numpy_to_pil(image), self.numpy_to_depth(image)
        else:
            raise Exception(f"This type {output_type} is not supported")