Aluode/PerceptionLabPortable
0
1# coding=utf-82# Copyright 2025 Meta Inc. and The HuggingFace Inc. team. All rights reserved.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15"""Fast Image processor class for Chameleon."""16 17from typing import Optional18 19import numpy as np20import PIL21import torch22from torchvision.transforms.v2 import functional as F23 24from ...image_processing_utils_fast import BaseImageProcessorFast25from ...image_utils import ImageInput, PILImageResampling, SizeDict26from ...utils import auto_docstring, logging27 28 29logger = logging.get_logger(__name__)30 31 32@auto_docstring33class ChameleonImageProcessorFast(BaseImageProcessorFast):34 resample = PILImageResampling.LANCZOS35 image_mean = [1.0, 1.0, 1.0]36 image_std = [1.0, 1.0, 1.0]37 size = {"shortest_edge": 512}38 default_to_square = False39 crop_size = {"height": 512, "width": 512}40 do_resize = True41 do_center_crop = True42 do_rescale = True43 rescale_factor = 0.007844 do_normalize = True45 do_convert_rgb = True46 47 def convert_to_rgb(self, image: ImageInput) -> ImageInput:48 """49 Convert image to RGB by blending the transparency layer if it's in RGBA format.50 If image is not `PIL.Image`, it si simply returned without modifications.51 52 Args:53 image (`ImageInput`):54 Image to convert.55 """56 57 if not isinstance(image, PIL.Image.Image):58 return image59 elif image.mode == "RGB":60 return image61 62 img_rgba = np.array(image.convert("RGBA"))63 64 # If there is no transparency layer, simple convert and return.65 if not (img_rgba[:, :, 3] < 255).any():66 return image.convert("RGB")67 68 # There is a transparency layer, blend it with a white background.69 # Calculate the alpha proportion for blending.70 alpha = img_rgba[:, :, 3] / 255.071 img_rgb = (1 - alpha[:, :, np.newaxis]) * 255 + alpha[:, :, np.newaxis] * img_rgba[:, :, :3]72 return PIL.Image.fromarray(img_rgb.astype("uint8"), "RGB")73 74 def resize(75 self,76 image: "torch.Tensor",77 size: SizeDict,78 interpolation: Optional["F.InterpolationMode"] = None,79 **kwargs,80 ) -> "torch.Tensor":81 """82 Resize an image to `(size["height"], size["width"])`.83 84 Args:85 image (`torch.Tensor`):86 Image to resize.87 size (`SizeDict`):88 Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.89 resample (`InterpolationMode`, *optional*, defaults to `InterpolationMode.BILINEAR`):90 `InterpolationMode` filter to use when resizing the image e.g. `InterpolationMode.BICUBIC`.91 92 Returns:93 `torch.Tensor`: The resized image.94 """95 interpolation = interpolation if interpolation is not None else F.InterpolationMode.BILINEAR96 if interpolation == F.InterpolationMode.LANCZOS:97 logger.warning_once(98 "You have used fast image processor with LANCZOS resample which not yet supported for torch.Tensor. "99 "BICUBIC resample will be used as an alternative. Please fall back to slow image processor if you "100 "want full consistency with the original model."101 )102 interpolation = F.InterpolationMode.BICUBIC103 104 return super().resize(105 image=image,106 size=size,107 interpolation=interpolation,108 **kwargs,109 )110 111 112__all__ = ["ChameleonImageProcessorFast"]113 