image_processor.py 25.2 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, Tuple, Union
YiYi Xu's avatar
YiYi Xu committed
17
18

import numpy as np
Anh71me's avatar
Anh71me committed
19
import PIL.Image
YiYi Xu's avatar
YiYi Xu committed
20
21
22
23
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
29
30
31
32
33
34
35
PipelineImageInput = Union[
    PIL.Image.Image,
    np.ndarray,
    torch.FloatTensor,
    List[PIL.Image.Image],
    List[np.ndarray],
    List[torch.FloatTensor],
]

36
37
38
39
40
41
42
43
44
PipelineDepthInput = Union[
    PIL.Image.Image,
    np.ndarray,
    torch.FloatTensor,
    List[PIL.Image.Image],
    List[np.ndarray],
    List[torch.FloatTensor],
]

45

YiYi Xu's avatar
YiYi Xu committed
46
47
class VaeImageProcessor(ConfigMixin):
    """
Steven Liu's avatar
Steven Liu committed
48
    Image processor for VAE.
YiYi Xu's avatar
YiYi Xu committed
49
50
51

    Args:
        do_resize (`bool`, *optional*, defaults to `True`):
52
            Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`. Can accept
Steven Liu's avatar
Steven Liu committed
53
            `height` and `width` arguments from [`image_processor.VaeImageProcessor.preprocess`] method.
YiYi Xu's avatar
YiYi Xu committed
54
        vae_scale_factor (`int`, *optional*, defaults to `8`):
Steven Liu's avatar
Steven Liu committed
55
            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
56
57
58
        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
59
            Whether to normalize the image to [-1,1].
60
        do_binarize (`bool`, *optional*, defaults to `False`):
61
            Whether to binarize the image to 0/1.
62
63
        do_convert_rgb (`bool`, *optional*, defaults to be `False`):
            Whether to convert the images to RGB format.
64
65
        do_convert_grayscale (`bool`, *optional*, defaults to be `False`):
            Whether to convert the images to grayscale format.
YiYi Xu's avatar
YiYi Xu committed
66
67
68
69
70
71
72
73
74
75
76
    """

    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,
77
        do_binarize: bool = False,
78
        do_convert_rgb: bool = False,
79
        do_convert_grayscale: bool = False,
YiYi Xu's avatar
YiYi Xu committed
80
81
    ):
        super().__init__()
82
83
84
85
86
87
88
        if do_convert_rgb and do_convert_grayscale:
            raise ValueError(
                "`do_convert_rgb` and `do_convert_grayscale` can not both be set to `True`,"
                " if you intended to convert the image into RGB format, please set `do_convert_grayscale = False`.",
                " if you intended to convert the image into grayscale format, please set `do_convert_rgb = False`",
            )
            self.config.do_convert_rgb = False
YiYi Xu's avatar
YiYi Xu committed
89
90

    @staticmethod
91
    def numpy_to_pil(images: np.ndarray) -> PIL.Image.Image:
YiYi Xu's avatar
YiYi Xu committed
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
        """
        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
107
108
    def pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
        """
Steven Liu's avatar
Steven Liu committed
109
        Convert a PIL image or a list of PIL images to NumPy arrays.
110
111
112
113
114
115
116
117
118
119
        """
        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
120
        """
Steven Liu's avatar
Steven Liu committed
121
        Convert a NumPy image to a PyTorch tensor.
YiYi Xu's avatar
YiYi Xu committed
122
123
124
125
126
127
128
129
        """
        if images.ndim == 3:
            images = images[..., None]

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

    @staticmethod
130
    def pt_to_numpy(images: torch.FloatTensor) -> np.ndarray:
YiYi Xu's avatar
YiYi Xu committed
131
        """
Steven Liu's avatar
Steven Liu committed
132
        Convert a PyTorch tensor to a NumPy image.
YiYi Xu's avatar
YiYi Xu committed
133
134
135
136
137
        """
        images = images.cpu().permute(0, 2, 3, 1).float().numpy()
        return images

    @staticmethod
138
    def normalize(images: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
YiYi Xu's avatar
YiYi Xu committed
139
        """
Steven Liu's avatar
Steven Liu committed
140
        Normalize an image array to [-1,1].
YiYi Xu's avatar
YiYi Xu committed
141
142
143
        """
        return 2.0 * images - 1.0

144
    @staticmethod
145
    def denormalize(images: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
146
        """
Steven Liu's avatar
Steven Liu committed
147
        Denormalize an image array to [0,1].
148
149
150
        """
        return (images / 2 + 0.5).clamp(0, 1)

151
152
153
    @staticmethod
    def convert_to_rgb(image: PIL.Image.Image) -> PIL.Image.Image:
        """
154
        Converts a PIL image to RGB format.
155
156
        """
        image = image.convert("RGB")
157

158
159
        return image

160
161
162
163
164
165
166
167
168
169
    @staticmethod
    def convert_to_grayscale(image: PIL.Image.Image) -> PIL.Image.Image:
        """
        Converts a PIL image to grayscale format.
        """
        image = image.convert("L")

        return image

    def get_default_height_width(
170
        self,
171
        image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
172
173
        height: Optional[int] = None,
        width: Optional[int] = None,
174
    ) -> Tuple[int, int]:
YiYi Xu's avatar
YiYi Xu committed
175
        """
176
177
178
179
180
181
182
183
184
185
186
187
        This function return the height and width that are downscaled to the next integer multiple of
        `vae_scale_factor`.

        Args:
            image(`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
                The image input, can be a PIL image, numpy array or pytorch tensor. if it is a numpy array, should have
                shape `[batch, height, width]` or `[batch, height, width, channel]` if it is a pytorch tensor, should
                have shape `[batch, channel, height, width]`.
            height (`int`, *optional*, defaults to `None`):
                The height in preprocessed image. If `None`, will use the height of `image` input.
            width (`int`, *optional*`, defaults to `None`):
                The width in preprocessed. If `None`, will use the width of the `image` input.
YiYi Xu's avatar
YiYi Xu committed
188
        """
189

190
        if height is None:
191
192
193
194
195
196
197
            if isinstance(image, PIL.Image.Image):
                height = image.height
            elif isinstance(image, torch.Tensor):
                height = image.shape[2]
            else:
                height = image.shape[1]

198
        if width is None:
199
200
201
202
203
            if isinstance(image, PIL.Image.Image):
                width = image.width
            elif isinstance(image, torch.Tensor):
                width = image.shape[3]
            else:
204
                width = image.shape[2]
205
206
207
208

        width, height = (
            x - x % self.config.vae_scale_factor for x in (width, height)
        )  # resize to integer multiple of vae_scale_factor
209
210
211
212
213

        return height, width

    def resize(
        self,
214
        image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
215
216
        height: Optional[int] = None,
        width: Optional[int] = None,
217
    ) -> Union[PIL.Image.Image, np.ndarray, torch.Tensor]:
218
        """
219
        Resize image.
220
221
222
223
224
225
226
227
228
229
230
231

        Args:
            image (`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
                The image input, can be a PIL image, numpy array or pytorch tensor.
            height (`int`, *optional*, defaults to `None`):
                The height to resize to.
            width (`int`, *optional*`, defaults to `None`):
                The width to resize to.

        Returns:
            `PIL.Image.Image`, `np.ndarray` or `torch.Tensor`:
                The resized image.
232
        """
233
234
235
236
237
238
239
240
241
242
243
244
245
246
        if isinstance(image, PIL.Image.Image):
            image = image.resize((width, height), resample=PIL_INTERPOLATION[self.config.resample])
        elif isinstance(image, torch.Tensor):
            image = torch.nn.functional.interpolate(
                image,
                size=(height, width),
            )
        elif isinstance(image, np.ndarray):
            image = self.numpy_to_pt(image)
            image = torch.nn.functional.interpolate(
                image,
                size=(height, width),
            )
            image = self.pt_to_numpy(image)
247
        return image
YiYi Xu's avatar
YiYi Xu committed
248

249
250
    def binarize(self, image: PIL.Image.Image) -> PIL.Image.Image:
        """
251
252
253
254
255
256
257
258
259
        Create a mask.

        Args:
            image (`PIL.Image.Image`):
                The image input, should be a PIL image.

        Returns:
            `PIL.Image.Image`:
                The binarized image. Values less than 0.5 are set to 0, values greater than 0.5 are set to 1.
260
261
262
263
264
        """
        image[image < 0.5] = 0
        image[image >= 0.5] = 1
        return image

YiYi Xu's avatar
YiYi Xu committed
265
266
267
    def preprocess(
        self,
        image: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
268
269
        height: Optional[int] = None,
        width: Optional[int] = None,
YiYi Xu's avatar
YiYi Xu committed
270
271
    ) -> torch.Tensor:
        """
Steven Liu's avatar
Steven Liu committed
272
        Preprocess the image input. Accepted formats are PIL images, NumPy arrays or PyTorch tensors.
YiYi Xu's avatar
YiYi Xu committed
273
274
        """
        supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293

        # Expand the missing dimension for 3-dimensional pytorch tensor or numpy array that represents grayscale image
        if self.config.do_convert_grayscale and isinstance(image, (torch.Tensor, np.ndarray)) and image.ndim == 3:
            if isinstance(image, torch.Tensor):
                # if image is a pytorch tensor could have 2 possible shapes:
                #    1. batch x height x width: we should insert the channel dimension at position 1
                #    2. channnel x height x width: we should insert batch dimension at position 0,
                #       however, since both channel and batch dimension has same size 1, it is same to insert at position 1
                #    for simplicity, we insert a dimension of size 1 at position 1 for both cases
                image = image.unsqueeze(1)
            else:
                # if it is a numpy array, it could have 2 possible shapes:
                #   1. batch x height x width: insert channel dimension on last position
                #   2. height x width x channel: insert batch dimension on first position
                if image.shape[-1] == 1:
                    image = np.expand_dims(image, axis=0)
                else:
                    image = np.expand_dims(image, axis=-1)

YiYi Xu's avatar
YiYi Xu committed
294
295
296
297
298
299
300
301
        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):
302
303
            if self.config.do_convert_rgb:
                image = [self.convert_to_rgb(i) for i in image]
304
305
            elif self.config.do_convert_grayscale:
                image = [self.convert_to_grayscale(i) for i in image]
306
            if self.config.do_resize:
307
                height, width = self.get_default_height_width(image[0], height, width)
308
309
                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
310
311
312
313
            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)
314

YiYi Xu's avatar
YiYi Xu committed
315
            image = self.numpy_to_pt(image)
316
317

            height, width = self.get_default_height_width(image, height, width)
318
319
            if self.config.do_resize:
                image = self.resize(image, height, width)
YiYi Xu's avatar
YiYi Xu committed
320
321
322

        elif isinstance(image[0], torch.Tensor):
            image = torch.cat(image, axis=0) if image[0].ndim == 4 else torch.stack(image, axis=0)
323

324
325
326
327
            if self.config.do_convert_grayscale and image.ndim == 3:
                image = image.unsqueeze(1)

            channel = image.shape[1]
328
329
330
331
            # don't need any preprocess if the image is latents
            if channel == 4:
                return image

332
            height, width = self.get_default_height_width(image, height, width)
333
334
            if self.config.do_resize:
                image = self.resize(image, height, width)
YiYi Xu's avatar
YiYi Xu committed
335
336

        # expected range [0,1], normalize to [-1,1]
337
        do_normalize = self.config.do_normalize
338
        if do_normalize and image.min() < 0:
YiYi Xu's avatar
YiYi Xu committed
339
340
341
342
343
344
345
346
347
348
            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)

349
350
351
        if self.config.do_binarize:
            image = self.binarize(image)

YiYi Xu's avatar
YiYi Xu committed
352
353
354
355
        return image

    def postprocess(
        self,
356
        image: torch.FloatTensor,
YiYi Xu's avatar
YiYi Xu committed
357
        output_type: str = "pil",
358
        do_denormalize: Optional[List[bool]] = None,
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
    ) -> Union[PIL.Image.Image, np.ndarray, torch.FloatTensor]:
        """
        Postprocess the image output from tensor to `output_type`.

        Args:
            image (`torch.FloatTensor`):
                The image input, should be a pytorch tensor with shape `B x C x H x W`.
            output_type (`str`, *optional*, defaults to `pil`):
                The output type of the image, can be one of `pil`, `np`, `pt`, `latent`.
            do_denormalize (`List[bool]`, *optional*, defaults to `None`):
                Whether to denormalize the image to [0,1]. If `None`, will use the value of `do_normalize` in the
                `VaeImageProcessor` config.

        Returns:
            `PIL.Image.Image`, `np.ndarray` or `torch.FloatTensor`:
                The postprocessed image.
        """
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
        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
399
400
401
402
403
404
            return image

        image = self.pt_to_numpy(image)

        if output_type == "np":
            return image
405
406

        if output_type == "pil":
YiYi Xu's avatar
YiYi Xu committed
407
            return self.numpy_to_pil(image)
estelleafl's avatar
estelleafl committed
408
409
410
411


class VaeImageProcessorLDM3D(VaeImageProcessor):
    """
Steven Liu's avatar
Steven Liu committed
412
    Image processor for VAE LDM3D.
estelleafl's avatar
estelleafl committed
413
414
415
416
417

    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
418
            VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
estelleafl's avatar
estelleafl committed
419
420
421
        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
422
            Whether to normalize the image to [-1,1].
estelleafl's avatar
estelleafl committed
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
    """

    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
438
    def numpy_to_pil(images: np.ndarray) -> List[PIL.Image.Image]:
estelleafl's avatar
estelleafl committed
439
        """
Steven Liu's avatar
Steven Liu committed
440
        Convert a NumPy image or a batch of images to a PIL image.
estelleafl's avatar
estelleafl committed
441
442
443
444
445
446
447
448
449
450
451
452
        """
        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

453
454
455
456
457
458
459
460
461
462
463
464
    @staticmethod
    def depth_pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
        """
        Convert a PIL image or a list of PIL images to NumPy arrays.
        """
        if not isinstance(images, list):
            images = [images]

        images = [np.array(image).astype(np.float32) / (2**16 - 1) for image in images]
        images = np.stack(images, axis=0)
        return images

estelleafl's avatar
estelleafl committed
465
    @staticmethod
466
    def rgblike_to_depthmap(image: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
estelleafl's avatar
estelleafl committed
467
468
469
470
471
472
473
474
475
        """
        Args:
            image: RGB-like depth image

        Returns: depth map

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

476
    def numpy_to_depth(self, images: np.ndarray) -> List[PIL.Image.Image]:
estelleafl's avatar
estelleafl committed
477
        """
Steven Liu's avatar
Steven Liu committed
478
        Convert a NumPy depth image or a batch of images to a PIL image.
estelleafl's avatar
estelleafl committed
479
480
481
        """
        if images.ndim == 3:
            images = images[None, ...]
482
483
484
485
486
487
488
489
490
        images_depth = images[:, :, :, 3:]
        if images.shape[-1] == 6:
            images_depth = (images_depth * 255).round().astype("uint8")
            pil_images = [
                Image.fromarray(self.rgblike_to_depthmap(image_depth), mode="I;16") for image_depth in images_depth
            ]
        elif images.shape[-1] == 4:
            images_depth = (images_depth * 65535.0).astype(np.uint16)
            pil_images = [Image.fromarray(image_depth, mode="I;16") for image_depth in images_depth]
estelleafl's avatar
estelleafl committed
491
        else:
492
            raise Exception("Not supported")
estelleafl's avatar
estelleafl committed
493
494
495
496
497
498
499
500

        return pil_images

    def postprocess(
        self,
        image: torch.FloatTensor,
        output_type: str = "pil",
        do_denormalize: Optional[List[bool]] = None,
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
    ) -> Union[PIL.Image.Image, np.ndarray, torch.FloatTensor]:
        """
        Postprocess the image output from tensor to `output_type`.

        Args:
            image (`torch.FloatTensor`):
                The image input, should be a pytorch tensor with shape `B x C x H x W`.
            output_type (`str`, *optional*, defaults to `pil`):
                The output type of the image, can be one of `pil`, `np`, `pt`, `latent`.
            do_denormalize (`List[bool]`, *optional*, defaults to `None`):
                Whether to denormalize the image to [0,1]. If `None`, will use the value of `do_normalize` in the
                `VaeImageProcessor` config.

        Returns:
            `PIL.Image.Image`, `np.ndarray` or `torch.FloatTensor`:
                The postprocessed image.
        """
estelleafl's avatar
estelleafl committed
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
        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":
540
541
542
543
544
            if image.shape[-1] == 6:
                image_depth = np.stack([self.rgblike_to_depthmap(im[:, :, 3:]) for im in image], axis=0)
            else:
                image_depth = image[:, :, :, 3:]
            return image[:, :, :, :3], image_depth
estelleafl's avatar
estelleafl committed
545
546
547
548
549

        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")
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648

    def preprocess(
        self,
        rgb: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
        depth: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
        height: Optional[int] = None,
        width: Optional[int] = None,
        target_res: Optional[int] = None,
    ) -> torch.Tensor:
        """
        Preprocess the image input. Accepted formats are PIL images, NumPy arrays or PyTorch tensors.
        """
        supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)

        # Expand the missing dimension for 3-dimensional pytorch tensor or numpy array that represents grayscale image
        if self.config.do_convert_grayscale and isinstance(rgb, (torch.Tensor, np.ndarray)) and rgb.ndim == 3:
            raise Exception("This is not yet supported")

        if isinstance(rgb, supported_formats):
            rgb = [rgb]
            depth = [depth]
        elif not (isinstance(rgb, list) and all(isinstance(i, supported_formats) for i in rgb)):
            raise ValueError(
                f"Input is in incorrect format: {[type(i) for i in rgb]}. Currently, we only support {', '.join(supported_formats)}"
            )

        if isinstance(rgb[0], PIL.Image.Image):
            if self.config.do_convert_rgb:
                raise Exception("This is not yet supported")
                # rgb = [self.convert_to_rgb(i) for i in rgb]
                # depth = [self.convert_to_depth(i) for i in depth]  #TODO define convert_to_depth
            if self.config.do_resize or target_res:
                height, width = self.get_default_height_width(rgb[0], height, width) if not target_res else target_res
                rgb = [self.resize(i, height, width) for i in rgb]
                depth = [self.resize(i, height, width) for i in depth]
            rgb = self.pil_to_numpy(rgb)  # to np
            rgb = self.numpy_to_pt(rgb)  # to pt

            depth = self.depth_pil_to_numpy(depth)  # to np
            depth = self.numpy_to_pt(depth)  # to pt

        elif isinstance(rgb[0], np.ndarray):
            rgb = np.concatenate(rgb, axis=0) if rgb[0].ndim == 4 else np.stack(rgb, axis=0)
            rgb = self.numpy_to_pt(rgb)
            height, width = self.get_default_height_width(rgb, height, width)
            if self.config.do_resize:
                rgb = self.resize(rgb, height, width)

            depth = np.concatenate(depth, axis=0) if rgb[0].ndim == 4 else np.stack(depth, axis=0)
            depth = self.numpy_to_pt(depth)
            height, width = self.get_default_height_width(depth, height, width)
            if self.config.do_resize:
                depth = self.resize(depth, height, width)

        elif isinstance(rgb[0], torch.Tensor):
            raise Exception("This is not yet supported")
            # rgb = torch.cat(rgb, axis=0) if rgb[0].ndim == 4 else torch.stack(rgb, axis=0)

            # if self.config.do_convert_grayscale and rgb.ndim == 3:
            #     rgb = rgb.unsqueeze(1)

            # channel = rgb.shape[1]

            # height, width = self.get_default_height_width(rgb, height, width)
            # if self.config.do_resize:
            #     rgb = self.resize(rgb, height, width)

            # depth = torch.cat(depth, axis=0) if depth[0].ndim == 4 else torch.stack(depth, axis=0)

            # if self.config.do_convert_grayscale and depth.ndim == 3:
            #     depth = depth.unsqueeze(1)

            # channel = depth.shape[1]
            # # don't need any preprocess if the image is latents
            # if depth == 4:
            #     return rgb, depth

            # height, width = self.get_default_height_width(depth, height, width)
            # if self.config.do_resize:
            #     depth = self.resize(depth, height, width)
        # expected range [0,1], normalize to [-1,1]
        do_normalize = self.config.do_normalize
        if rgb.min() < 0 and do_normalize:
            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 [{rgb.min()},{rgb.max()}]",
                FutureWarning,
            )
            do_normalize = False

        if do_normalize:
            rgb = self.normalize(rgb)
            depth = self.normalize(depth)

        if self.config.do_binarize:
            rgb = self.binarize(rgb)
            depth = self.binarize(depth)

        return rgb, depth