image_processor.py 57.2 KB
Newer Older
Aryan's avatar
Aryan committed
1
# Copyright 2025 The HuggingFace Team. All rights reserved.
YiYi Xu's avatar
YiYi Xu committed
2
3
4
5
6
7
8
9
10
11
12
13
14
#
# 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.

15
import math
YiYi Xu's avatar
YiYi Xu committed
16
import warnings
17
from typing import List, Optional, Tuple, Union
YiYi Xu's avatar
YiYi Xu committed
18
19

import numpy as np
Anh71me's avatar
Anh71me committed
20
import PIL.Image
YiYi Xu's avatar
YiYi Xu committed
21
import torch
22
import torch.nn.functional as F
23
from PIL import Image, ImageFilter, ImageOps
YiYi Xu's avatar
YiYi Xu committed
24
25

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


29
30
31
PipelineImageInput = Union[
    PIL.Image.Image,
    np.ndarray,
32
    torch.Tensor,
33
34
    List[PIL.Image.Image],
    List[np.ndarray],
35
    List[torch.Tensor],
36
37
]

38
PipelineDepthInput = PipelineImageInput
39

40

41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def is_valid_image(image) -> bool:
    r"""
    Checks if the input is a valid image.

    A valid image can be:
    - A `PIL.Image.Image`.
    - A 2D or 3D `np.ndarray` or `torch.Tensor` (grayscale or color image).

    Args:
        image (`Union[PIL.Image.Image, np.ndarray, torch.Tensor]`):
            The image to validate. It can be a PIL image, a NumPy array, or a torch tensor.

    Returns:
        `bool`:
            `True` if the input is a valid image, `False` otherwise.
    """
57
58
59
60
    return isinstance(image, PIL.Image.Image) or isinstance(image, (np.ndarray, torch.Tensor)) and image.ndim in (2, 3)


def is_valid_image_imagelist(images):
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
    r"""
    Checks if the input is a valid image or list of images.

    The input can be one of the following formats:
    - A 4D tensor or numpy array (batch of images).
    - A valid single image: `PIL.Image.Image`, 2D `np.ndarray` or `torch.Tensor` (grayscale image), 3D `np.ndarray` or
      `torch.Tensor`.
    - A list of valid images.

    Args:
        images (`Union[np.ndarray, torch.Tensor, PIL.Image.Image, List]`):
            The image(s) to check. Can be a batch of images (4D tensor/array), a single image, or a list of valid
            images.

    Returns:
        `bool`:
            `True` if the input is valid, `False` otherwise.
    """
79
80
81
82
83
84
85
86
87
    if isinstance(images, (np.ndarray, torch.Tensor)) and images.ndim == 4:
        return True
    elif is_valid_image(images):
        return True
    elif isinstance(images, list):
        return all(is_valid_image(image) for image in images)
    return False


YiYi Xu's avatar
YiYi Xu committed
88
89
class VaeImageProcessor(ConfigMixin):
    """
Steven Liu's avatar
Steven Liu committed
90
    Image processor for VAE.
YiYi Xu's avatar
YiYi Xu committed
91
92
93

    Args:
        do_resize (`bool`, *optional*, defaults to `True`):
94
            Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`. Can accept
Steven Liu's avatar
Steven Liu committed
95
            `height` and `width` arguments from [`image_processor.VaeImageProcessor.preprocess`] method.
YiYi Xu's avatar
YiYi Xu committed
96
        vae_scale_factor (`int`, *optional*, defaults to `8`):
Steven Liu's avatar
Steven Liu committed
97
            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
98
99
100
        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
101
            Whether to normalize the image to [-1,1].
102
        do_binarize (`bool`, *optional*, defaults to `False`):
103
            Whether to binarize the image to 0/1.
104
105
        do_convert_rgb (`bool`, *optional*, defaults to be `False`):
            Whether to convert the images to RGB format.
106
107
        do_convert_grayscale (`bool`, *optional*, defaults to be `False`):
            Whether to convert the images to grayscale format.
YiYi Xu's avatar
YiYi Xu committed
108
109
110
111
112
113
114
115
116
    """

    config_name = CONFIG_NAME

    @register_to_config
    def __init__(
        self,
        do_resize: bool = True,
        vae_scale_factor: int = 8,
Dhruv Nair's avatar
Dhruv Nair committed
117
        vae_latent_channels: int = 4,
YiYi Xu's avatar
YiYi Xu committed
118
        resample: str = "lanczos",
119
        reducing_gap: int = None,
YiYi Xu's avatar
YiYi Xu committed
120
        do_normalize: bool = True,
121
        do_binarize: bool = False,
122
        do_convert_rgb: bool = False,
123
        do_convert_grayscale: bool = False,
YiYi Xu's avatar
YiYi Xu committed
124
125
    ):
        super().__init__()
126
127
128
129
130
131
        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`",
            )
YiYi Xu's avatar
YiYi Xu committed
132
133

    @staticmethod
134
    def numpy_to_pil(images: np.ndarray) -> List[PIL.Image.Image]:
135
        r"""
YiYi Xu's avatar
YiYi Xu committed
136
        Convert a numpy image or a batch of images to a PIL image.
137
138
139
140
141
142
143
144

        Args:
            images (`np.ndarray`):
                The image array to convert to PIL format.

        Returns:
            `List[PIL.Image.Image]`:
                A list of PIL images.
YiYi Xu's avatar
YiYi Xu committed
145
146
147
148
149
150
151
152
153
154
155
156
157
        """
        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
158
    def pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
159
        r"""
Steven Liu's avatar
Steven Liu committed
160
        Convert a PIL image or a list of PIL images to NumPy arrays.
161
162
163
164
165
166
167
168

        Args:
            images (`PIL.Image.Image` or `List[PIL.Image.Image]`):
                The PIL image or list of images to convert to NumPy format.

        Returns:
            `np.ndarray`:
                A NumPy array representation of the images.
169
170
171
172
173
174
175
176
177
        """
        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
178
    def numpy_to_pt(images: np.ndarray) -> torch.Tensor:
179
        r"""
Steven Liu's avatar
Steven Liu committed
180
        Convert a NumPy image to a PyTorch tensor.
181
182
183
184
185
186
187
188

        Args:
            images (`np.ndarray`):
                The NumPy image array to convert to PyTorch format.

        Returns:
            `torch.Tensor`:
                A PyTorch tensor representation of the images.
YiYi Xu's avatar
YiYi Xu committed
189
190
191
192
193
194
195
196
        """
        if images.ndim == 3:
            images = images[..., None]

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

    @staticmethod
197
    def pt_to_numpy(images: torch.Tensor) -> np.ndarray:
198
        r"""
Steven Liu's avatar
Steven Liu committed
199
        Convert a PyTorch tensor to a NumPy image.
200
201
202
203
204
205
206
207

        Args:
            images (`torch.Tensor`):
                The PyTorch tensor to convert to NumPy format.

        Returns:
            `np.ndarray`:
                A NumPy array representation of the images.
YiYi Xu's avatar
YiYi Xu committed
208
209
210
211
212
        """
        images = images.cpu().permute(0, 2, 3, 1).float().numpy()
        return images

    @staticmethod
213
    def normalize(images: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
214
        r"""
Steven Liu's avatar
Steven Liu committed
215
        Normalize an image array to [-1,1].
216
217
218
219
220
221
222
223

        Args:
            images (`np.ndarray` or `torch.Tensor`):
                The image array to normalize.

        Returns:
            `np.ndarray` or `torch.Tensor`:
                The normalized image array.
YiYi Xu's avatar
YiYi Xu committed
224
225
226
        """
        return 2.0 * images - 1.0

227
    @staticmethod
228
    def denormalize(images: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
229
        r"""
Steven Liu's avatar
Steven Liu committed
230
        Denormalize an image array to [0,1].
231
232
233
234
235
236
237
238

        Args:
            images (`np.ndarray` or `torch.Tensor`):
                The image array to denormalize.

        Returns:
            `np.ndarray` or `torch.Tensor`:
                The denormalized image array.
239
        """
240
        return (images * 0.5 + 0.5).clamp(0, 1)
241

242
243
    @staticmethod
    def convert_to_rgb(image: PIL.Image.Image) -> PIL.Image.Image:
244
        r"""
245
        Converts a PIL image to RGB format.
246
247
248
249
250
251
252
253

        Args:
            image (`PIL.Image.Image`):
                The PIL image to convert to RGB.

        Returns:
            `PIL.Image.Image`:
                The RGB-converted PIL image.
254
255
        """
        image = image.convert("RGB")
256

257
258
        return image

259
260
    @staticmethod
    def convert_to_grayscale(image: PIL.Image.Image) -> PIL.Image.Image:
261
262
263
264
265
266
267
268
269
270
        r"""
        Converts a given PIL image to grayscale.

        Args:
            image (`PIL.Image.Image`):
                The input image to convert.

        Returns:
            `PIL.Image.Image`:
                The image converted to grayscale.
271
272
273
274
275
        """
        image = image.convert("L")

        return image

276
277
    @staticmethod
    def blur(image: PIL.Image.Image, blur_factor: int = 4) -> PIL.Image.Image:
278
        r"""
279
        Applies Gaussian blur to an image.
280
281
282
283
284
285
286
287

        Args:
            image (`PIL.Image.Image`):
                The PIL image to convert to grayscale.

        Returns:
            `PIL.Image.Image`:
                The grayscale-converted PIL image.
288
289
290
291
292
293
294
        """
        image = image.filter(ImageFilter.GaussianBlur(blur_factor))

        return image

    @staticmethod
    def get_crop_region(mask_image: PIL.Image.Image, width: int, height: int, pad=0):
295
        r"""
296
297
298
        Finds a rectangular region that contains all masked ares in an image, and expands region to match the aspect
        ratio of the original image; for example, if user drew mask in a 128x32 region, and the dimensions for
        processing are 512x512, the region will be expanded to 128x128.
299
300
301
302
303
304
305
306

        Args:
            mask_image (PIL.Image.Image): Mask image.
            width (int): Width of the image to be processed.
            height (int): Height of the image to be processed.
            pad (int, optional): Padding to be added to the crop region. Defaults to 0.

        Returns:
307
308
            tuple: (x1, y1, x2, y2) represent a rectangular region that contains all masked ares in an image and
            matches the original aspect ratio.
309
310
311
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
        """

        mask_image = mask_image.convert("L")
        mask = np.array(mask_image)

        # 1. find a rectangular region that contains all masked ares in an image
        h, w = mask.shape
        crop_left = 0
        for i in range(w):
            if not (mask[:, i] == 0).all():
                break
            crop_left += 1

        crop_right = 0
        for i in reversed(range(w)):
            if not (mask[:, i] == 0).all():
                break
            crop_right += 1

        crop_top = 0
        for i in range(h):
            if not (mask[i] == 0).all():
                break
            crop_top += 1

        crop_bottom = 0
        for i in reversed(range(h)):
            if not (mask[i] == 0).all():
                break
            crop_bottom += 1

        # 2. add padding to the crop region
        x1, y1, x2, y2 = (
            int(max(crop_left - pad, 0)),
            int(max(crop_top - pad, 0)),
            int(min(w - crop_right + pad, w)),
            int(min(h - crop_bottom + pad, h)),
        )

        # 3. expands crop region to match the aspect ratio of the image to be processed
        ratio_crop_region = (x2 - x1) / (y2 - y1)
        ratio_processing = width / height

        if ratio_crop_region > ratio_processing:
            desired_height = (x2 - x1) / ratio_processing
            desired_height_diff = int(desired_height - (y2 - y1))
            y1 -= desired_height_diff // 2
            y2 += desired_height_diff - desired_height_diff // 2
            if y2 >= mask_image.height:
                diff = y2 - mask_image.height
                y2 -= diff
                y1 -= diff
            if y1 < 0:
                y2 -= y1
                y1 -= y1
            if y2 >= mask_image.height:
                y2 = mask_image.height
        else:
            desired_width = (y2 - y1) * ratio_processing
            desired_width_diff = int(desired_width - (x2 - x1))
            x1 -= desired_width_diff // 2
            x2 += desired_width_diff - desired_width_diff // 2
            if x2 >= mask_image.width:
                diff = x2 - mask_image.width
                x2 -= diff
                x1 -= diff
            if x1 < 0:
                x2 -= x1
                x1 -= x1
            if x2 >= mask_image.width:
                x2 = mask_image.width

        return x1, y1, x2, y2

    def _resize_and_fill(
384
        self,
385
386
387
388
        image: PIL.Image.Image,
        width: int,
        height: int,
    ) -> PIL.Image.Image:
389
        r"""
390
391
        Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center
        the image within the dimensions, filling empty with data from image.
392
393

        Args:
394
395
396
397
398
399
400
401
402
403
            image (`PIL.Image.Image`):
                The image to resize and fill.
            width (`int`):
                The width to resize the image to.
            height (`int`):
                The height to resize the image to.

        Returns:
            `PIL.Image.Image`:
                The resized and filled image.
YiYi Xu's avatar
YiYi Xu committed
404
        """
405

406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
        ratio = width / height
        src_ratio = image.width / image.height

        src_w = width if ratio < src_ratio else image.width * height // image.height
        src_h = height if ratio >= src_ratio else image.height * width // image.width

        resized = image.resize((src_w, src_h), resample=PIL_INTERPOLATION["lanczos"])
        res = Image.new("RGB", (width, height))
        res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))

        if ratio < src_ratio:
            fill_height = height // 2 - src_h // 2
            if fill_height > 0:
                res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0))
                res.paste(
                    resized.resize((width, fill_height), box=(0, resized.height, width, resized.height)),
                    box=(0, fill_height + src_h),
                )
        elif ratio > src_ratio:
            fill_width = width // 2 - src_w // 2
            if fill_width > 0:
                res.paste(resized.resize((fill_width, height), box=(0, 0, 0, height)), box=(0, 0))
                res.paste(
                    resized.resize((fill_width, height), box=(resized.width, 0, resized.width, height)),
                    box=(fill_width + src_w, 0),
                )

        return res

    def _resize_and_crop(
        self,
        image: PIL.Image.Image,
        width: int,
        height: int,
    ) -> PIL.Image.Image:
441
        r"""
442
443
        Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center
        the image within the dimensions, cropping the excess.
444

445
        Args:
446
447
448
449
450
451
452
453
454
455
            image (`PIL.Image.Image`):
                The image to resize and crop.
            width (`int`):
                The width to resize the image to.
            height (`int`):
                The height to resize the image to.

        Returns:
            `PIL.Image.Image`:
                The resized and cropped image.
456
457
458
        """
        ratio = width / height
        src_ratio = image.width / image.height
459

460
461
        src_w = width if ratio > src_ratio else image.width * height // image.height
        src_h = height if ratio <= src_ratio else image.height * width // image.width
462

463
464
465
466
        resized = image.resize((src_w, src_h), resample=PIL_INTERPOLATION["lanczos"])
        res = Image.new("RGB", (width, height))
        res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
        return res
467
468
469

    def resize(
        self,
470
        image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
471
472
        height: int,
        width: int,
M. Tolga Cangöz's avatar
M. Tolga Cangöz committed
473
        resize_mode: str = "default",  # "default", "fill", "crop"
474
    ) -> Union[PIL.Image.Image, np.ndarray, torch.Tensor]:
475
        """
476
        Resize image.
477
478
479
480

        Args:
            image (`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
                The image input, can be a PIL image, numpy array or pytorch tensor.
481
            height (`int`):
482
                The height to resize to.
483
            width (`int`):
484
                The width to resize to.
485
486
            resize_mode (`str`, *optional*, defaults to `default`):
                The resize mode to use, can be one of `default` or `fill`. If `default`, will resize the image to fit
487
488
489
490
491
492
                within the specified width and height, and it may not maintaining the original aspect ratio. If `fill`,
                will resize the image to fit within the specified width and height, maintaining the aspect ratio, and
                then center the image within the dimensions, filling empty with data from image. If `crop`, will resize
                the image to fit within the specified width and height, maintaining the aspect ratio, and then center
                the image within the dimensions, cropping the excess. Note that resize_mode `fill` and `crop` are only
                supported for PIL image input.
493
494
495
496

        Returns:
            `PIL.Image.Image`, `np.ndarray` or `torch.Tensor`:
                The resized image.
497
        """
498
499
        if resize_mode != "default" and not isinstance(image, PIL.Image.Image):
            raise ValueError(f"Only PIL image input is supported for resize_mode {resize_mode}")
500
        if isinstance(image, PIL.Image.Image):
501
            if resize_mode == "default":
502
503
504
505
506
                image = image.resize(
                    (width, height),
                    resample=PIL_INTERPOLATION[self.config.resample],
                    reducing_gap=self.config.reducing_gap,
                )
507
508
509
510
511
512
513
            elif resize_mode == "fill":
                image = self._resize_and_fill(image, width, height)
            elif resize_mode == "crop":
                image = self._resize_and_crop(image, width, height)
            else:
                raise ValueError(f"resize_mode {resize_mode} is not supported")

514
515
516
517
518
519
520
521
522
523
524
525
        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)
YiYi Xu's avatar
YiYi Xu committed
526

527
        return image
YiYi Xu's avatar
YiYi Xu committed
528

529
530
    def binarize(self, image: PIL.Image.Image) -> PIL.Image.Image:
        """
531
532
533
534
535
536
537
538
539
        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.
540
541
542
        """
        image[image < 0.5] = 0
        image[image >= 0.5] = 1
543

544
545
        return image

546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
    def _denormalize_conditionally(
        self, images: torch.Tensor, do_denormalize: Optional[List[bool]] = None
    ) -> torch.Tensor:
        r"""
        Denormalize a batch of images based on a condition list.

        Args:
            images (`torch.Tensor`):
                The input image tensor.
            do_denormalize (`Optional[List[bool]`, *optional*, defaults to `None`):
                A list of booleans indicating whether to denormalize each image in the batch. If `None`, will use the
                value of `do_normalize` in the `VaeImageProcessor` config.
        """
        if do_denormalize is None:
            return self.denormalize(images) if self.config.do_normalize else images

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

566
567
568
569
570
571
    def get_default_height_width(
        self,
        image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
        height: Optional[int] = None,
        width: Optional[int] = None,
    ) -> Tuple[int, int]:
572
573
        r"""
        Returns the height and width of the image, downscaled to the next integer multiple of `vae_scale_factor`.
574
575

        Args:
576
577
578
579
580
581
582
583
584
585
586
587
588
            image (`Union[PIL.Image.Image, np.ndarray, torch.Tensor]`):
                The image input, which can be a PIL image, NumPy array, or PyTorch tensor. If it is a NumPy array, it
                should have shape `[batch, height, width]` or `[batch, height, width, channels]`. If it is a PyTorch
                tensor, it should have shape `[batch, channels, height, width]`.
            height (`Optional[int]`, *optional*, defaults to `None`):
                The height of the preprocessed image. If `None`, the height of the `image` input will be used.
            width (`Optional[int]`, *optional*, defaults to `None`):
                The width of the preprocessed image. If `None`, the width of the `image` input will be used.

        Returns:
            `Tuple[int, int]`:
                A tuple containing the height and width, both resized to the nearest integer multiple of
                `vae_scale_factor`.
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
        """

        if height is None:
            if isinstance(image, PIL.Image.Image):
                height = image.height
            elif isinstance(image, torch.Tensor):
                height = image.shape[2]
            else:
                height = image.shape[1]

        if width is None:
            if isinstance(image, PIL.Image.Image):
                width = image.width
            elif isinstance(image, torch.Tensor):
                width = image.shape[3]
            else:
                width = image.shape[2]

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

        return height, width

YiYi Xu's avatar
YiYi Xu committed
613
614
    def preprocess(
        self,
615
        image: PipelineImageInput,
616
617
        height: Optional[int] = None,
        width: Optional[int] = None,
M. Tolga Cangöz's avatar
M. Tolga Cangöz committed
618
        resize_mode: str = "default",  # "default", "fill", "crop"
619
        crops_coords: Optional[Tuple[int, int, int, int]] = None,
YiYi Xu's avatar
YiYi Xu committed
620
621
    ) -> torch.Tensor:
        """
622
623
624
        Preprocess the image input.

        Args:
625
            image (`PipelineImageInput`):
626
627
                The image input, accepted formats are PIL images, NumPy arrays, PyTorch tensors; Also accept list of
                supported formats.
628
            height (`int`, *optional*):
629
630
                The height in preprocessed image. If `None`, will use the `get_default_height_width()` to get default
                height.
631
            width (`int`, *optional*):
632
                The width in preprocessed. If `None`, will use get_default_height_width()` to get the default width.
633
            resize_mode (`str`, *optional*, defaults to `default`):
634
635
636
637
638
639
640
                The resize mode, can be one of `default` or `fill`. If `default`, will resize the image to fit within
                the specified width and height, and it may not maintaining the original aspect ratio. If `fill`, will
                resize the image to fit within the specified width and height, maintaining the aspect ratio, and then
                center the image within the dimensions, filling empty with data from image. If `crop`, will resize the
                image to fit within the specified width and height, maintaining the aspect ratio, and then center the
                image within the dimensions, cropping the excess. Note that resize_mode `fill` and `crop` are only
                supported for PIL image input.
641
642
            crops_coords (`List[Tuple[int, int, int, int]]`, *optional*, defaults to `None`):
                The crop coordinates for each image in the batch. If `None`, will not crop the image.
643
644
645
646

        Returns:
            `torch.Tensor`:
                The preprocessed image.
YiYi Xu's avatar
YiYi Xu committed
647
648
        """
        supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
649
650
651
652
653
654

        # 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
M. Tolga Cangöz's avatar
M. Tolga Cangöz committed
655
                #    2. channel x height x width: we should insert batch dimension at position 0,
656
657
658
659
660
661
662
663
664
665
666
667
                #       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)

668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
        if isinstance(image, list) and isinstance(image[0], np.ndarray) and image[0].ndim == 4:
            warnings.warn(
                "Passing `image` as a list of 4d np.ndarray is deprecated."
                "Please concatenate the list along the batch dimension and pass it as a single 4d np.ndarray",
                FutureWarning,
            )
            image = np.concatenate(image, axis=0)
        if isinstance(image, list) and isinstance(image[0], torch.Tensor) and image[0].ndim == 4:
            warnings.warn(
                "Passing `image` as a list of 4d torch.Tensor is deprecated."
                "Please concatenate the list along the batch dimension and pass it as a single 4d torch.Tensor",
                FutureWarning,
            )
            image = torch.cat(image, axis=0)

        if not is_valid_image_imagelist(image):
YiYi Xu's avatar
YiYi Xu committed
684
            raise ValueError(
685
                f"Input is in incorrect format. Currently, we only support {', '.join(str(x) for x in supported_formats)}"
YiYi Xu's avatar
YiYi Xu committed
686
            )
687
688
        if not isinstance(image, list):
            image = [image]
YiYi Xu's avatar
YiYi Xu committed
689
690

        if isinstance(image[0], PIL.Image.Image):
691
692
693
694
695
            if crops_coords is not None:
                image = [i.crop(crops_coords) for i in image]
            if self.config.do_resize:
                height, width = self.get_default_height_width(image[0], height, width)
                image = [self.resize(i, height, width, resize_mode=resize_mode) for i in image]
696
697
            if self.config.do_convert_rgb:
                image = [self.convert_to_rgb(i) for i in image]
698
699
            elif self.config.do_convert_grayscale:
                image = [self.convert_to_grayscale(i) for i in image]
700
            image = self.pil_to_numpy(image)  # to np
YiYi Xu's avatar
YiYi Xu committed
701
702
703
704
            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)
705

YiYi Xu's avatar
YiYi Xu committed
706
            image = self.numpy_to_pt(image)
707
708

            height, width = self.get_default_height_width(image, height, width)
709
710
            if self.config.do_resize:
                image = self.resize(image, height, width)
YiYi Xu's avatar
YiYi Xu committed
711
712
713

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

715
716
717
718
            if self.config.do_convert_grayscale and image.ndim == 3:
                image = image.unsqueeze(1)

            channel = image.shape[1]
719
            # don't need any preprocess if the image is latents
720
            if channel == self.config.vae_latent_channels:
721
722
                return image

723
            height, width = self.get_default_height_width(image, height, width)
724
725
            if self.config.do_resize:
                image = self.resize(image, height, width)
YiYi Xu's avatar
YiYi Xu committed
726
727

        # expected range [0,1], normalize to [-1,1]
728
        do_normalize = self.config.do_normalize
729
        if do_normalize and image.min() < 0:
YiYi Xu's avatar
YiYi Xu committed
730
731
732
733
734
735
736
737
738
            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)

739
740
741
        if self.config.do_binarize:
            image = self.binarize(image)

YiYi Xu's avatar
YiYi Xu committed
742
743
744
745
        return image

    def postprocess(
        self,
746
        image: torch.Tensor,
YiYi Xu's avatar
YiYi Xu committed
747
        output_type: str = "pil",
748
        do_denormalize: Optional[List[bool]] = None,
749
    ) -> Union[PIL.Image.Image, np.ndarray, torch.Tensor]:
750
751
752
753
        """
        Postprocess the image output from tensor to `output_type`.

        Args:
754
            image (`torch.Tensor`):
755
756
757
758
759
760
761
762
                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:
763
            `PIL.Image.Image`, `np.ndarray` or `torch.Tensor`:
764
765
                The postprocessed image.
        """
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
        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

781
        image = self._denormalize_conditionally(image, do_denormalize)
782
783

        if output_type == "pt":
YiYi Xu's avatar
YiYi Xu committed
784
785
786
787
788
789
            return image

        image = self.pt_to_numpy(image)

        if output_type == "np":
            return image
790
791

        if output_type == "pil":
YiYi Xu's avatar
YiYi Xu committed
792
            return self.numpy_to_pil(image)
estelleafl's avatar
estelleafl committed
793

794
795
796
797
798
799
800
    def apply_overlay(
        self,
        mask: PIL.Image.Image,
        init_image: PIL.Image.Image,
        image: PIL.Image.Image,
        crop_coords: Optional[Tuple[int, int, int, int]] = None,
    ) -> PIL.Image.Image:
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
        r"""
        Applies an overlay of the mask and the inpainted image on the original image.

        Args:
            mask (`PIL.Image.Image`):
                The mask image that highlights regions to overlay.
            init_image (`PIL.Image.Image`):
                The original image to which the overlay is applied.
            image (`PIL.Image.Image`):
                The image to overlay onto the original.
            crop_coords (`Tuple[int, int, int, int]`, *optional*):
                Coordinates to crop the image. If provided, the image will be cropped accordingly.

        Returns:
            `PIL.Image.Image`:
                The final image with the overlay applied.
817
818
        """

819
        width, height = init_image.width, init_image.height
820
821
822

        init_image_masked = PIL.Image.new("RGBa", (width, height))
        init_image_masked.paste(init_image.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(mask.convert("L")))
823

824
825
826
        init_image_masked = init_image_masked.convert("RGBA")

        if crop_coords is not None:
827
828
829
            x, y, x2, y2 = crop_coords
            w = x2 - x
            h = y2 - y
830
831
832
833
834
835
836
837
838
839
840
            base_image = PIL.Image.new("RGBA", (width, height))
            image = self.resize(image, height=h, width=w, resize_mode="crop")
            base_image.paste(image, (x, y))
            image = base_image.convert("RGB")

        image = image.convert("RGBA")
        image.alpha_composite(init_image_masked)
        image = image.convert("RGB")

        return image

estelleafl's avatar
estelleafl committed
841

YiYi Xu's avatar
YiYi Xu committed
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
class InpaintProcessor(ConfigMixin):
    """
    Image processor for inpainting image and mask.
    """

    config_name = CONFIG_NAME

    @register_to_config
    def __init__(
        self,
        do_resize: bool = True,
        vae_scale_factor: int = 8,
        vae_latent_channels: int = 4,
        resample: str = "lanczos",
        reducing_gap: int = None,
        do_normalize: bool = True,
        do_binarize: bool = False,
        do_convert_grayscale: bool = False,
        mask_do_normalize: bool = False,
        mask_do_binarize: bool = True,
        mask_do_convert_grayscale: bool = True,
    ):
        super().__init__()

        self._image_processor = VaeImageProcessor(
            do_resize=do_resize,
            vae_scale_factor=vae_scale_factor,
            vae_latent_channels=vae_latent_channels,
            resample=resample,
            reducing_gap=reducing_gap,
            do_normalize=do_normalize,
            do_binarize=do_binarize,
            do_convert_grayscale=do_convert_grayscale,
        )
        self._mask_processor = VaeImageProcessor(
            do_resize=do_resize,
            vae_scale_factor=vae_scale_factor,
            vae_latent_channels=vae_latent_channels,
            resample=resample,
            reducing_gap=reducing_gap,
            do_normalize=mask_do_normalize,
            do_binarize=mask_do_binarize,
            do_convert_grayscale=mask_do_convert_grayscale,
        )

    def preprocess(
        self,
        image: PIL.Image.Image,
        mask: PIL.Image.Image = None,
        height: int = None,
        width: int = None,
        padding_mask_crop: Optional[int] = None,
    ) -> Tuple[torch.Tensor, torch.Tensor]:
        """
        Preprocess the image and mask.
        """
        if mask is None and padding_mask_crop is not None:
            raise ValueError("mask must be provided if padding_mask_crop is provided")

        # if mask is None, same behavior as regular image processor
        if mask is None:
            return self._image_processor.preprocess(image, height=height, width=width)

        if padding_mask_crop is not None:
            crops_coords = self._image_processor.get_crop_region(mask, width, height, pad=padding_mask_crop)
            resize_mode = "fill"
        else:
            crops_coords = None
            resize_mode = "default"

        processed_image = self._image_processor.preprocess(
            image,
            height=height,
            width=width,
            crops_coords=crops_coords,
            resize_mode=resize_mode,
        )

        processed_mask = self._mask_processor.preprocess(
            mask,
            height=height,
            width=width,
            resize_mode=resize_mode,
            crops_coords=crops_coords,
        )

        if crops_coords is not None:
            postprocessing_kwargs = {
                "crops_coords": crops_coords,
                "original_image": image,
                "original_mask": mask,
            }
        else:
            postprocessing_kwargs = {
                "crops_coords": None,
                "original_image": None,
                "original_mask": None,
            }

        return processed_image, processed_mask, postprocessing_kwargs

    def postprocess(
        self,
        image: torch.Tensor,
        output_type: str = "pil",
        original_image: Optional[PIL.Image.Image] = None,
        original_mask: Optional[PIL.Image.Image] = None,
        crops_coords: Optional[Tuple[int, int, int, int]] = None,
    ) -> Tuple[PIL.Image.Image, PIL.Image.Image]:
        """
        Postprocess the image, optionally apply mask overlay
        """
        image = self._image_processor.postprocess(
            image,
            output_type=output_type,
        )
        # optionally apply the mask overlay
        if crops_coords is not None and (original_image is None or original_mask is None):
            raise ValueError("original_image and original_mask must be provided if crops_coords is provided")

        elif crops_coords is not None and output_type != "pil":
            raise ValueError("output_type must be 'pil' if crops_coords is provided")

        elif crops_coords is not None:
            image = [
                self._image_processor.apply_overlay(original_mask, original_image, i, crops_coords) for i in image
            ]

        return image


estelleafl's avatar
estelleafl committed
973
974
class VaeImageProcessorLDM3D(VaeImageProcessor):
    """
Steven Liu's avatar
Steven Liu committed
975
    Image processor for VAE LDM3D.
estelleafl's avatar
estelleafl committed
976
977
978
979
980

    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
981
            VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
estelleafl's avatar
estelleafl committed
982
983
984
        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
985
            Whether to normalize the image to [-1,1].
estelleafl's avatar
estelleafl committed
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    """

    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
1001
    def numpy_to_pil(images: np.ndarray) -> List[PIL.Image.Image]:
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
        r"""
        Convert a NumPy image or a batch of images to a list of PIL images.

        Args:
            images (`np.ndarray`):
                The input NumPy array of images, which can be a single image or a batch.

        Returns:
            `List[PIL.Image.Image]`:
                A list of PIL images converted from the input NumPy array.
estelleafl's avatar
estelleafl committed
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
        """
        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

1024
1025
    @staticmethod
    def depth_pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
1026
        r"""
1027
        Convert a PIL image or a list of PIL images to NumPy arrays.
1028
1029
1030
1031
1032
1033
1034
1035

        Args:
            images (`Union[List[PIL.Image.Image], PIL.Image.Image]`):
                The input image or list of images to be converted.

        Returns:
            `np.ndarray`:
                A NumPy array of the converted images.
1036
1037
1038
1039
1040
1041
1042
1043
        """
        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
1044
    @staticmethod
1045
    def rgblike_to_depthmap(image: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
1046
1047
        r"""
        Convert an RGB-like depth image to a depth map.
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
        """
        # 1. Cast the tensor to a larger integer type (e.g., int32)
        #    to safely perform the multiplication by 256.
        # 2. Perform the 16-bit combination: High-byte * 256 + Low-byte.
        # 3. Cast the final result to the desired depth map type (uint16) if needed
        #    before returning, though leaving it as int32/int64 is often safer
        #    for return value from a library function.

        if isinstance(image, torch.Tensor):
            # Cast to a safe dtype (e.g., int32 or int64) for the calculation
            original_dtype = image.dtype
            image_safe = image.to(torch.int32)

            # Calculate the depth map
            depth_map = image_safe[:, :, 1] * 256 + image_safe[:, :, 2]

            # You may want to cast the final result to uint16, but casting to a
            # larger int type (like int32) is sufficient to fix the overflow.
            # depth_map = depth_map.to(torch.uint16) # Uncomment if uint16 is strictly required
            return depth_map.to(original_dtype)
estelleafl's avatar
estelleafl committed
1068

1069
1070
1071
1072
        elif isinstance(image, np.ndarray):
            # NumPy equivalent: Cast to a safe dtype (e.g., np.int32)
            original_dtype = image.dtype
            image_safe = image.astype(np.int32)
estelleafl's avatar
estelleafl committed
1073

1074
1075
1076
1077
1078
1079
1080
            # Calculate the depth map
            depth_map = image_safe[:, :, 1] * 256 + image_safe[:, :, 2]

            # depth_map = depth_map.astype(np.uint16) # Uncomment if uint16 is strictly required
            return depth_map.astype(original_dtype)
        else:
            raise TypeError("Input image must be a torch.Tensor or np.ndarray")
estelleafl's avatar
estelleafl committed
1081

1082
    def numpy_to_depth(self, images: np.ndarray) -> List[PIL.Image.Image]:
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
        r"""
        Convert a NumPy depth image or a batch of images to a list of PIL images.

        Args:
            images (`np.ndarray`):
                The input NumPy array of depth images, which can be a single image or a batch.

        Returns:
            `List[PIL.Image.Image]`:
                A list of PIL images converted from the input NumPy depth images.
estelleafl's avatar
estelleafl committed
1093
1094
1095
        """
        if images.ndim == 3:
            images = images[None, ...]
1096
1097
1098
1099
1100
1101
1102
1103
1104
        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
1105
        else:
1106
            raise Exception("Not supported")
estelleafl's avatar
estelleafl committed
1107
1108
1109
1110
1111

        return pil_images

    def postprocess(
        self,
1112
        image: torch.Tensor,
estelleafl's avatar
estelleafl committed
1113
1114
        output_type: str = "pil",
        do_denormalize: Optional[List[bool]] = None,
1115
    ) -> Union[PIL.Image.Image, np.ndarray, torch.Tensor]:
1116
1117
1118
1119
        """
        Postprocess the image output from tensor to `output_type`.

        Args:
1120
            image (`torch.Tensor`):
1121
1122
1123
1124
1125
1126
1127
1128
                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:
1129
            `PIL.Image.Image`, `np.ndarray` or `torch.Tensor`:
1130
1131
                The postprocessed image.
        """
estelleafl's avatar
estelleafl committed
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
        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"

1144
        image = self._denormalize_conditionally(image, do_denormalize)
estelleafl's avatar
estelleafl committed
1145
1146
1147
1148

        image = self.pt_to_numpy(image)

        if output_type == "np":
1149
1150
1151
1152
1153
            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
1154
1155
1156
1157
1158

        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")
1159
1160
1161

    def preprocess(
        self,
1162
1163
        rgb: Union[torch.Tensor, PIL.Image.Image, np.ndarray],
        depth: Union[torch.Tensor, PIL.Image.Image, np.ndarray],
1164
1165
1166
1167
        height: Optional[int] = None,
        width: Optional[int] = None,
        target_res: Optional[int] = None,
    ) -> torch.Tensor:
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
        r"""
        Preprocess the image input. Accepted formats are PIL images, NumPy arrays, or PyTorch tensors.

        Args:
            rgb (`Union[torch.Tensor, PIL.Image.Image, np.ndarray]`):
                The RGB input image, which can be a single image or a batch.
            depth (`Union[torch.Tensor, PIL.Image.Image, np.ndarray]`):
                The depth input image, which can be a single image or a batch.
            height (`Optional[int]`, *optional*, defaults to `None`):
                The desired height of the processed image. If `None`, defaults to the height of the input image.
            width (`Optional[int]`, *optional*, defaults to `None`):
                The desired width of the processed image. If `None`, defaults to the width of the input image.
            target_res (`Optional[int]`, *optional*, defaults to `None`):
                Target resolution for resizing the images. If specified, overrides height and width.

        Returns:
            `Tuple[torch.Tensor, torch.Tensor]`:
                A tuple containing the processed RGB and depth images as PyTorch tensors.
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
        """
        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
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317


class IPAdapterMaskProcessor(VaeImageProcessor):
    """
    Image processor for IP Adapter image masks.

    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`):
            VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
        resample (`str`, *optional*, defaults to `lanczos`):
            Resampling filter to use when resizing the image.
        do_normalize (`bool`, *optional*, defaults to `False`):
            Whether to normalize the image to [-1,1].
        do_binarize (`bool`, *optional*, defaults to `True`):
            Whether to binarize the image to 0/1.
        do_convert_grayscale (`bool`, *optional*, defaults to be `True`):
            Whether to convert the images to grayscale format.

    """

    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 = False,
        do_binarize: bool = True,
        do_convert_grayscale: bool = True,
    ):
        super().__init__(
            do_resize=do_resize,
            vae_scale_factor=vae_scale_factor,
            resample=resample,
            do_normalize=do_normalize,
            do_binarize=do_binarize,
            do_convert_grayscale=do_convert_grayscale,
        )

    @staticmethod
1318
    def downsample(mask: torch.Tensor, batch_size: int, num_queries: int, value_embed_dim: int):
1319
        """
1320
1321
        Downsamples the provided mask tensor to match the expected dimensions for scaled dot-product attention. If the
        aspect ratio of the mask does not match the aspect ratio of the output image, a warning is issued.
1322
1323

        Args:
1324
            mask (`torch.Tensor`):
1325
1326
1327
1328
1329
1330
1331
1332
1333
                The input mask tensor generated with `IPAdapterMaskProcessor.preprocess()`.
            batch_size (`int`):
                The batch size.
            num_queries (`int`):
                The number of queries.
            value_embed_dim (`int`):
                The dimensionality of the value embeddings.

        Returns:
1334
            `torch.Tensor`:
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
                The downsampled mask tensor.

        """
        o_h = mask.shape[1]
        o_w = mask.shape[2]
        ratio = o_w / o_h
        mask_h = int(math.sqrt(num_queries / ratio))
        mask_h = int(mask_h) + int((num_queries % int(mask_h)) != 0)
        mask_w = num_queries // mask_h

        mask_downsample = F.interpolate(mask.unsqueeze(0), size=(mask_h, mask_w), mode="bicubic").squeeze(0)

        # Repeat batch_size times
        if mask_downsample.shape[0] < batch_size:
            mask_downsample = mask_downsample.repeat(batch_size, 1, 1)

        mask_downsample = mask_downsample.view(mask_downsample.shape[0], -1)

        downsampled_area = mask_h * mask_w
        # If the output image and the mask do not have the same aspect ratio, tensor shapes will not match
        # Pad tensor if downsampled_mask.shape[1] is smaller than num_queries
        if downsampled_area < num_queries:
            warnings.warn(
                "The aspect ratio of the mask does not match the aspect ratio of the output image. "
                "Please update your masks or adjust the output size for optimal performance.",
                UserWarning,
            )
            mask_downsample = F.pad(mask_downsample, (0, num_queries - mask_downsample.shape[1]), value=0.0)
        # Discard last embeddings if downsampled_mask.shape[1] is bigger than num_queries
        if downsampled_area > num_queries:
            warnings.warn(
                "The aspect ratio of the mask does not match the aspect ratio of the output image. "
                "Please update your masks or adjust the output size for optimal performance.",
                UserWarning,
            )
            mask_downsample = mask_downsample[:, :num_queries]

        # Repeat last dimension to match SDPA output shape
        mask_downsample = mask_downsample.view(mask_downsample.shape[0], mask_downsample.shape[1], 1).repeat(
            1, 1, value_embed_dim
        )

        return mask_downsample
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422


class PixArtImageProcessor(VaeImageProcessor):
    """
    Image processor for PixArt image resize and crop.

    Args:
        do_resize (`bool`, *optional*, defaults to `True`):
            Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`. Can accept
            `height` and `width` arguments from [`image_processor.VaeImageProcessor.preprocess`] method.
        vae_scale_factor (`int`, *optional*, defaults to `8`):
            VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
        resample (`str`, *optional*, defaults to `lanczos`):
            Resampling filter to use when resizing the image.
        do_normalize (`bool`, *optional*, defaults to `True`):
            Whether to normalize the image to [-1,1].
        do_binarize (`bool`, *optional*, defaults to `False`):
            Whether to binarize the image to 0/1.
        do_convert_rgb (`bool`, *optional*, defaults to be `False`):
            Whether to convert the images to RGB format.
        do_convert_grayscale (`bool`, *optional*, defaults to be `False`):
            Whether to convert the images to grayscale format.
    """

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

    @staticmethod
    def classify_height_width_bin(height: int, width: int, ratios: dict) -> Tuple[int, int]:
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
        r"""
        Returns the binned height and width based on the aspect ratio.

        Args:
            height (`int`): The height of the image.
            width (`int`): The width of the image.
            ratios (`dict`): A dictionary where keys are aspect ratios and values are tuples of (height, width).

        Returns:
            `Tuple[int, int]`: The closest binned height and width.
        """
1434
1435
1436
1437
1438
1439
1440
        ar = float(height / width)
        closest_ratio = min(ratios.keys(), key=lambda ratio: abs(float(ratio) - ar))
        default_hw = ratios[closest_ratio]
        return int(default_hw[0]), int(default_hw[1])

    @staticmethod
    def resize_and_crop_tensor(samples: torch.Tensor, new_width: int, new_height: int) -> torch.Tensor:
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
        r"""
        Resizes and crops a tensor of images to the specified dimensions.

        Args:
            samples (`torch.Tensor`):
                A tensor of shape (N, C, H, W) where N is the batch size, C is the number of channels, H is the height,
                and W is the width.
            new_width (`int`): The desired width of the output images.
            new_height (`int`): The desired height of the output images.

        Returns:
            `torch.Tensor`: A tensor containing the resized and cropped images.
        """
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
        orig_height, orig_width = samples.shape[2], samples.shape[3]

        # Check if resizing is needed
        if orig_height != new_height or orig_width != new_width:
            ratio = max(new_height / orig_height, new_width / orig_width)
            resized_width = int(orig_width * ratio)
            resized_height = int(orig_height * ratio)

            # Resize
            samples = F.interpolate(
                samples, size=(resized_height, resized_width), mode="bilinear", align_corners=False
            )

            # Center Crop
            start_x = (resized_width - new_width) // 2
            end_x = start_x + new_width
            start_y = (resized_height - new_height) // 2
            end_y = start_y + new_height
            samples = samples[:, :, start_y:end_y, start_x:end_x]

        return samples