image_processing_glpn.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. # coding=utf-8
  2. # Copyright 2022 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 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. """Image processor class for GLPN."""
  16. from typing import List, Optional, Union
  17. import numpy as np
  18. import PIL.Image
  19. from ...image_processing_utils import BaseImageProcessor, BatchFeature
  20. from ...image_transforms import resize, to_channel_dimension_format
  21. from ...image_utils import (
  22. ChannelDimension,
  23. PILImageResampling,
  24. get_image_size,
  25. infer_channel_dimension_format,
  26. is_scaled_image,
  27. make_list_of_images,
  28. to_numpy_array,
  29. valid_images,
  30. validate_preprocess_arguments,
  31. )
  32. from ...utils import TensorType, filter_out_non_signature_kwargs, logging
  33. logger = logging.get_logger(__name__)
  34. class GLPNImageProcessor(BaseImageProcessor):
  35. r"""
  36. Constructs a GLPN image processor.
  37. Args:
  38. do_resize (`bool`, *optional*, defaults to `True`):
  39. Whether to resize the image's (height, width) dimensions, rounding them down to the closest multiple of
  40. `size_divisor`. Can be overridden by `do_resize` in `preprocess`.
  41. size_divisor (`int`, *optional*, defaults to 32):
  42. When `do_resize` is `True`, images are resized so their height and width are rounded down to the closest
  43. multiple of `size_divisor`. Can be overridden by `size_divisor` in `preprocess`.
  44. resample (`PIL.Image` resampling filter, *optional*, defaults to `Resampling.BILINEAR`):
  45. Resampling filter to use if resizing the image. Can be overridden by `resample` in `preprocess`.
  46. do_rescale (`bool`, *optional*, defaults to `True`):
  47. Whether or not to apply the scaling factor (to make pixel values floats between 0. and 1.). Can be
  48. overridden by `do_rescale` in `preprocess`.
  49. """
  50. model_input_names = ["pixel_values"]
  51. def __init__(
  52. self,
  53. do_resize: bool = True,
  54. size_divisor: int = 32,
  55. resample=PILImageResampling.BILINEAR,
  56. do_rescale: bool = True,
  57. **kwargs,
  58. ) -> None:
  59. self.do_resize = do_resize
  60. self.do_rescale = do_rescale
  61. self.size_divisor = size_divisor
  62. self.resample = resample
  63. super().__init__(**kwargs)
  64. def resize(
  65. self,
  66. image: np.ndarray,
  67. size_divisor: int,
  68. resample: PILImageResampling = PILImageResampling.BILINEAR,
  69. data_format: Optional[ChannelDimension] = None,
  70. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  71. **kwargs,
  72. ) -> np.ndarray:
  73. """
  74. Resize the image, rounding the (height, width) dimensions down to the closest multiple of size_divisor.
  75. If the image is of dimension (3, 260, 170) and size_divisor is 32, the image will be resized to (3, 256, 160).
  76. Args:
  77. image (`np.ndarray`):
  78. The image to resize.
  79. size_divisor (`int`):
  80. The image is resized so its height and width are rounded down to the closest multiple of
  81. `size_divisor`.
  82. resample:
  83. `PIL.Image` resampling filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
  84. data_format (`ChannelDimension` or `str`, *optional*):
  85. The channel dimension format for the output image. If `None`, the channel dimension format of the input
  86. image is used. Can be one of:
  87. - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  88. - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  89. input_data_format (`ChannelDimension` or `str`, *optional*):
  90. The channel dimension format of the input image. If not set, the channel dimension format is inferred
  91. from the input image. Can be one of:
  92. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  93. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  94. Returns:
  95. `np.ndarray`: The resized image.
  96. """
  97. height, width = get_image_size(image, channel_dim=input_data_format)
  98. # Rounds the height and width down to the closest multiple of size_divisor
  99. new_h = height // size_divisor * size_divisor
  100. new_w = width // size_divisor * size_divisor
  101. image = resize(
  102. image,
  103. (new_h, new_w),
  104. resample=resample,
  105. data_format=data_format,
  106. input_data_format=input_data_format,
  107. **kwargs,
  108. )
  109. return image
  110. @filter_out_non_signature_kwargs()
  111. def preprocess(
  112. self,
  113. images: Union["PIL.Image.Image", TensorType, List["PIL.Image.Image"], List[TensorType]],
  114. do_resize: Optional[bool] = None,
  115. size_divisor: Optional[int] = None,
  116. resample=None,
  117. do_rescale: Optional[bool] = None,
  118. return_tensors: Optional[Union[TensorType, str]] = None,
  119. data_format: ChannelDimension = ChannelDimension.FIRST,
  120. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  121. ) -> BatchFeature:
  122. """
  123. Preprocess the given images.
  124. Args:
  125. images (`PIL.Image.Image` or `TensorType` or `List[np.ndarray]` or `List[TensorType]`):
  126. Images to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
  127. passing in images with pixel values between 0 and 1, set `do_normalize=False`.
  128. do_resize (`bool`, *optional*, defaults to `self.do_resize`):
  129. Whether to resize the input such that the (height, width) dimensions are a multiple of `size_divisor`.
  130. size_divisor (`int`, *optional*, defaults to `self.size_divisor`):
  131. When `do_resize` is `True`, images are resized so their height and width are rounded down to the
  132. closest multiple of `size_divisor`.
  133. resample (`PIL.Image` resampling filter, *optional*, defaults to `self.resample`):
  134. `PIL.Image` resampling filter to use if resizing the image e.g. `PILImageResampling.BILINEAR`. Only has
  135. an effect if `do_resize` is set to `True`.
  136. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
  137. Whether or not to apply the scaling factor (to make pixel values floats between 0. and 1.).
  138. return_tensors (`str` or `TensorType`, *optional*):
  139. The type of tensors to return. Can be one of:
  140. - `None`: Return a list of `np.ndarray`.
  141. - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
  142. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
  143. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
  144. - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
  145. data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
  146. The channel dimension format for the output image. Can be one of:
  147. - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  148. - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  149. input_data_format (`ChannelDimension` or `str`, *optional*):
  150. The channel dimension format for the input image. If unset, the channel dimension format is inferred
  151. from the input image. Can be one of:
  152. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  153. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  154. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  155. """
  156. do_resize = do_resize if do_resize is not None else self.do_resize
  157. do_rescale = do_rescale if do_rescale is not None else self.do_rescale
  158. size_divisor = size_divisor if size_divisor is not None else self.size_divisor
  159. resample = resample if resample is not None else self.resample
  160. images = make_list_of_images(images)
  161. if not valid_images(images):
  162. raise ValueError(
  163. "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
  164. "torch.Tensor, tf.Tensor or jax.ndarray."
  165. )
  166. # Here, the rescale() method uses a constant rescale_factor. It does not need to be validated
  167. # with a rescale_factor.
  168. validate_preprocess_arguments(
  169. do_resize=do_resize,
  170. size=size_divisor, # Here, size_divisor is used as a parameter for optimal resizing instead of size.
  171. resample=resample,
  172. )
  173. # All transformations expect numpy arrays.
  174. images = [to_numpy_array(img) for img in images]
  175. if is_scaled_image(images[0]) and do_rescale:
  176. logger.warning_once(
  177. "It looks like you are trying to rescale already rescaled images. If the input"
  178. " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
  179. )
  180. if input_data_format is None:
  181. # We assume that all images have the same channel dimension format.
  182. input_data_format = infer_channel_dimension_format(images[0])
  183. if do_resize:
  184. images = [
  185. self.resize(image, size_divisor=size_divisor, resample=resample, input_data_format=input_data_format)
  186. for image in images
  187. ]
  188. if do_rescale:
  189. images = [self.rescale(image, scale=1 / 255, input_data_format=input_data_format) for image in images]
  190. images = [
  191. to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
  192. ]
  193. data = {"pixel_values": images}
  194. return BatchFeature(data=data, tensor_type=return_tensors)