|
| 1 | +# coding=utf-8 |
| 2 | +# Copyright 2022 The HuggingFace Inc. team. |
| 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 at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# 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 and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +from typing import TYPE_CHECKING, List, Optional, Tuple, Union |
| 17 | + |
| 18 | +import numpy as np |
| 19 | + |
| 20 | +from transformers.utils.import_utils import is_flax_available, is_tf_available, is_torch_available, is_vision_available |
| 21 | + |
| 22 | + |
| 23 | +if is_vision_available(): |
| 24 | + import PIL |
| 25 | + |
| 26 | + from .image_utils import ( |
| 27 | + ChannelDimension, |
| 28 | + get_image_size, |
| 29 | + infer_channel_dimension_format, |
| 30 | + is_jax_tensor, |
| 31 | + is_tf_tensor, |
| 32 | + is_torch_tensor, |
| 33 | + ) |
| 34 | + |
| 35 | + |
| 36 | +if TYPE_CHECKING: |
| 37 | + if is_torch_available(): |
| 38 | + import torch |
| 39 | + if is_tf_available(): |
| 40 | + import tensorflow as tf |
| 41 | + if is_flax_available(): |
| 42 | + import jax.numpy as jnp |
| 43 | + |
| 44 | + |
| 45 | +def to_channel_dimension_format(image: np.ndarray, channel_dim: Union[ChannelDimension, str]) -> np.ndarray: |
| 46 | + """ |
| 47 | + Converts `image` to the channel dimension format specified by `channel_dim`. |
| 48 | +
|
| 49 | + Args: |
| 50 | + image (`numpy.ndarray`): |
| 51 | + The image to have its channel dimension set. |
| 52 | + channel_dim (`ChannelDimension`): |
| 53 | + The channel dimension format to use. |
| 54 | +
|
| 55 | + Returns: |
| 56 | + `np.ndarray`: The image with the channel dimension set to `channel_dim`. |
| 57 | + """ |
| 58 | + if not isinstance(image, np.ndarray): |
| 59 | + raise ValueError(f"Input image must be of type np.ndarray, got {type(image)}") |
| 60 | + |
| 61 | + current_channel_dim = infer_channel_dimension_format(image) |
| 62 | + target_channel_dim = ChannelDimension(channel_dim) |
| 63 | + if current_channel_dim == target_channel_dim: |
| 64 | + return image |
| 65 | + |
| 66 | + if target_channel_dim == ChannelDimension.FIRST: |
| 67 | + image = image.transpose((2, 0, 1)) |
| 68 | + elif target_channel_dim == ChannelDimension.LAST: |
| 69 | + image = image.transpose((1, 2, 0)) |
| 70 | + else: |
| 71 | + raise ValueError("Unsupported channel dimension format: {}".format(channel_dim)) |
| 72 | + |
| 73 | + return image |
| 74 | + |
| 75 | + |
| 76 | +def rescale( |
| 77 | + image: np.ndarray, scale: float, data_format: Optional[ChannelDimension] = None, dtype=np.float32 |
| 78 | +) -> np.ndarray: |
| 79 | + """ |
| 80 | + Rescales `image` by `scale`. |
| 81 | +
|
| 82 | + Args: |
| 83 | + image (`np.ndarray`): |
| 84 | + The image to rescale. |
| 85 | + scale (`float`): |
| 86 | + The scale to use for rescaling the image. |
| 87 | + data_format (`ChannelDimension`, *optional*): |
| 88 | + The channel dimension format of the image. If not provided, it will be the same as the input image. |
| 89 | + dtype (`np.dtype`, *optional*, defaults to `np.float32`): |
| 90 | + The dtype of the output image. Defaults to `np.float32`. Used for backwards compatibility with feature |
| 91 | + extractors. |
| 92 | +
|
| 93 | + Returns: |
| 94 | + `np.ndarray`: The rescaled image. |
| 95 | + """ |
| 96 | + if not isinstance(image, np.ndarray): |
| 97 | + raise ValueError(f"Input image must be of type np.ndarray, got {type(image)}") |
| 98 | + |
| 99 | + rescaled_image = image * scale |
| 100 | + if data_format is not None: |
| 101 | + rescaled_image = to_channel_dimension_format(rescaled_image, data_format) |
| 102 | + rescaled_image = rescaled_image.astype(dtype) |
| 103 | + return rescaled_image |
| 104 | + |
| 105 | + |
| 106 | +def to_pil_image( |
| 107 | + image: Union[np.ndarray, PIL.Image.Image, "torch.Tensor", "tf.Tensor", "jnp.Tensor"], |
| 108 | + do_rescale: Optional[bool] = None, |
| 109 | +) -> PIL.Image.Image: |
| 110 | + """ |
| 111 | + Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if |
| 112 | + needed. |
| 113 | +
|
| 114 | + Args: |
| 115 | + image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor` or `tf.Tensor`): |
| 116 | + The image to convert to the `PIL.Image` format. |
| 117 | + do_rescale (`bool`, *optional*): |
| 118 | + Whether or not to apply the scaling factor (to make pixel values integers between 0 and 255). Will default |
| 119 | + to `True` if the image type is a floating type, `False` otherwise. |
| 120 | +
|
| 121 | + Returns: |
| 122 | + `PIL.Image.Image`: The converted image. |
| 123 | + """ |
| 124 | + if isinstance(image, PIL.Image.Image): |
| 125 | + return image |
| 126 | + |
| 127 | + # Convert all tensors to numpy arrays before converting to PIL image |
| 128 | + if is_torch_tensor(image) or is_tf_tensor(image): |
| 129 | + image = image.numpy() |
| 130 | + elif is_jax_tensor(image): |
| 131 | + image = np.array(image) |
| 132 | + elif not isinstance(image, np.ndarray): |
| 133 | + raise ValueError("Input image type not supported: {}".format(type(image))) |
| 134 | + |
| 135 | + # If the channel as been moved to first dim, we put it back at the end. |
| 136 | + image = to_channel_dimension_format(image, ChannelDimension.LAST) |
| 137 | + |
| 138 | + # PIL.Image can only store uint8 values, so we rescale the image to be between 0 and 255 if needed. |
| 139 | + do_rescale = isinstance(image.flat[0], float) if do_rescale is None else do_rescale |
| 140 | + if do_rescale: |
| 141 | + image = rescale(image, 255) |
| 142 | + image = image.astype(np.uint8) |
| 143 | + return PIL.Image.fromarray(image) |
| 144 | + |
| 145 | + |
| 146 | +def get_resize_output_image_size( |
| 147 | + input_image: np.ndarray, |
| 148 | + size: Union[int, Tuple[int, int], List[int], Tuple[int]], |
| 149 | + default_to_square: bool = True, |
| 150 | + max_size: Optional[int] = None, |
| 151 | +) -> tuple: |
| 152 | + """ |
| 153 | + Find the target (height, width) dimension of the output image after resizing given the input image and the desired |
| 154 | + size. |
| 155 | +
|
| 156 | + Args: |
| 157 | + input_image (`np.ndarray`): |
| 158 | + The image to resize. |
| 159 | + size (`int` or `Tuple[int, int]` or List[int] or Tuple[int]): |
| 160 | + The size to use for resizing the image. If `size` is a sequence like (h, w), output size will be matched to |
| 161 | + this. |
| 162 | +
|
| 163 | + If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If |
| 164 | + `size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to this |
| 165 | + number. i.e, if height > width, then image will be rescaled to (size * height / width, size). |
| 166 | + default_to_square (`bool`, *optional*, defaults to `True`): |
| 167 | + How to convert `size` when it is a single int. If set to `True`, the `size` will be converted to a square |
| 168 | + (`size`,`size`). If set to `False`, will replicate |
| 169 | + [`torchvision.transforms.Resize`](https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.Resize) |
| 170 | + with support for resizing only the smallest edge and providing an optional `max_size`. |
| 171 | + max_size (`int`, *optional*): |
| 172 | + The maximum allowed for the longer edge of the resized image: if the longer edge of the image is greater |
| 173 | + than `max_size` after being resized according to `size`, then the image is resized again so that the longer |
| 174 | + edge is equal to `max_size`. As a result, `size` might be overruled, i.e the smaller edge may be shorter |
| 175 | + than `size`. Only used if `default_to_square` is `False`. |
| 176 | +
|
| 177 | + Returns: |
| 178 | + `tuple`: The target (height, width) dimension of the output image after resizing. |
| 179 | + """ |
| 180 | + if isinstance(size, (tuple, list)): |
| 181 | + if len(size) == 2: |
| 182 | + return tuple(size) |
| 183 | + elif len(size) == 1: |
| 184 | + # Perform same logic as if size was an int |
| 185 | + size = size[0] |
| 186 | + else: |
| 187 | + raise ValueError("size must have 1 or 2 elements if it is a list or tuple") |
| 188 | + |
| 189 | + if default_to_square: |
| 190 | + return (size, size) |
| 191 | + |
| 192 | + height, width = get_image_size(input_image) |
| 193 | + short, long = (width, height) if width <= height else (height, width) |
| 194 | + requested_new_short = size |
| 195 | + |
| 196 | + if short == requested_new_short: |
| 197 | + return (height, width) |
| 198 | + |
| 199 | + new_short, new_long = requested_new_short, int(requested_new_short * long / short) |
| 200 | + |
| 201 | + if max_size is not None: |
| 202 | + if max_size <= requested_new_short: |
| 203 | + raise ValueError( |
| 204 | + f"max_size = {max_size} must be strictly greater than the requested " |
| 205 | + f"size for the smaller edge size = {size}" |
| 206 | + ) |
| 207 | + if new_long > max_size: |
| 208 | + new_short, new_long = int(max_size * new_short / new_long), max_size |
| 209 | + |
| 210 | + return (new_long, new_short) if width <= height else (new_short, new_long) |
| 211 | + |
| 212 | + |
| 213 | +def resize( |
| 214 | + image, |
| 215 | + size: Tuple[int, int], |
| 216 | + resample=PIL.Image.BILINEAR, |
| 217 | + data_format: Optional[ChannelDimension] = None, |
| 218 | + return_numpy: bool = True, |
| 219 | +) -> np.ndarray: |
| 220 | + """ |
| 221 | + Resizes `image` to (h, w) specified by `size` using the PIL library. |
| 222 | +
|
| 223 | + Args: |
| 224 | + image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`): |
| 225 | + The image to resize. |
| 226 | + size (`Tuple[int, int]`): |
| 227 | + The size to use for resizing the image. |
| 228 | + resample (`int`, *optional*, defaults to `PIL.Image.BILINEAR`): |
| 229 | + The filter to user for resampling. |
| 230 | + data_format (`ChannelDimension`, *optional*): |
| 231 | + The channel dimension format of the output image. If `None`, will use the inferred format from the input. |
| 232 | + return_numpy (`bool`, *optional*, defaults to `True`): |
| 233 | + Whether or not to return the resized image as a numpy array. If False a `PIL.Image.Image` object is |
| 234 | + returned. |
| 235 | +
|
| 236 | + Returns: |
| 237 | + `np.ndarray`: The resized image. |
| 238 | + """ |
| 239 | + if not len(size) == 2: |
| 240 | + raise ValueError("size must have 2 elements") |
| 241 | + |
| 242 | + # For all transformations, we want to keep the same data format as the input image unless otherwise specified. |
| 243 | + # The resized image from PIL will always have channels last, so find the input format first. |
| 244 | + data_format = infer_channel_dimension_format(image) if data_format is None else data_format |
| 245 | + |
| 246 | + # To maintain backwards compatibility with the resizing done in previous image feature extractors, we use |
| 247 | + # the pillow library to resize the image and then convert back to numpy |
| 248 | + if not isinstance(image, PIL.Image.Image): |
| 249 | + # PIL expects image to have channels last |
| 250 | + image = to_channel_dimension_format(image, ChannelDimension.LAST) |
| 251 | + image = to_pil_image(image) |
| 252 | + height, width = size |
| 253 | + # PIL images are in the format (width, height) |
| 254 | + resized_image = image.resize((width, height), resample=resample) |
| 255 | + |
| 256 | + if return_numpy: |
| 257 | + resized_image = np.array(resized_image) |
| 258 | + resized_image = to_channel_dimension_format(resized_image, data_format) |
| 259 | + return resized_image |
0 commit comments