image_processing_vit.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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 ViT."""
  16. from typing import Dict, List, Optional, Union
  17. import numpy as np
  18. from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
  19. from ...image_transforms import resize, to_channel_dimension_format
  20. from ...image_utils import (
  21. IMAGENET_STANDARD_MEAN,
  22. IMAGENET_STANDARD_STD,
  23. ChannelDimension,
  24. ImageInput,
  25. PILImageResampling,
  26. infer_channel_dimension_format,
  27. is_scaled_image,
  28. make_list_of_images,
  29. to_numpy_array,
  30. valid_images,
  31. validate_preprocess_arguments,
  32. )
  33. from ...utils import TensorType, filter_out_non_signature_kwargs, logging
  34. logger = logging.get_logger(__name__)
  35. class ViTImageProcessor(BaseImageProcessor):
  36. r"""
  37. Constructs a ViT image processor.
  38. Args:
  39. do_resize (`bool`, *optional*, defaults to `True`):
  40. Whether to resize the image's (height, width) dimensions to the specified `(size["height"],
  41. size["width"])`. Can be overridden by the `do_resize` parameter in the `preprocess` method.
  42. size (`dict`, *optional*, defaults to `{"height": 224, "width": 224}`):
  43. Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess`
  44. method.
  45. resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
  46. Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
  47. `preprocess` method.
  48. do_rescale (`bool`, *optional*, defaults to `True`):
  49. Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
  50. parameter in the `preprocess` method.
  51. rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
  52. Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
  53. `preprocess` method.
  54. do_normalize (`bool`, *optional*, defaults to `True`):
  55. Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
  56. method.
  57. image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
  58. Mean to use if normalizing the image. This is a float or list of floats the length of the number of
  59. channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
  60. image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
  61. Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
  62. number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
  63. """
  64. model_input_names = ["pixel_values"]
  65. def __init__(
  66. self,
  67. do_resize: bool = True,
  68. size: Optional[Dict[str, int]] = None,
  69. resample: PILImageResampling = PILImageResampling.BILINEAR,
  70. do_rescale: bool = True,
  71. rescale_factor: Union[int, float] = 1 / 255,
  72. do_normalize: bool = True,
  73. image_mean: Optional[Union[float, List[float]]] = None,
  74. image_std: Optional[Union[float, List[float]]] = None,
  75. **kwargs,
  76. ) -> None:
  77. super().__init__(**kwargs)
  78. size = size if size is not None else {"height": 224, "width": 224}
  79. size = get_size_dict(size)
  80. self.do_resize = do_resize
  81. self.do_rescale = do_rescale
  82. self.do_normalize = do_normalize
  83. self.size = size
  84. self.resample = resample
  85. self.rescale_factor = rescale_factor
  86. self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
  87. self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
  88. def resize(
  89. self,
  90. image: np.ndarray,
  91. size: Dict[str, int],
  92. resample: PILImageResampling = PILImageResampling.BILINEAR,
  93. data_format: Optional[Union[str, ChannelDimension]] = None,
  94. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  95. **kwargs,
  96. ) -> np.ndarray:
  97. """
  98. Resize an image to `(size["height"], size["width"])`.
  99. Args:
  100. image (`np.ndarray`):
  101. Image to resize.
  102. size (`Dict[str, int]`):
  103. Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
  104. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
  105. `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
  106. data_format (`ChannelDimension` or `str`, *optional*):
  107. The channel dimension format for the output image. If unset, the channel dimension format of the input
  108. image is used. Can be one of:
  109. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  110. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  111. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  112. input_data_format (`ChannelDimension` or `str`, *optional*):
  113. The channel dimension format for the input image. If unset, the channel dimension format is inferred
  114. from the input image. Can be one of:
  115. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  116. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  117. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  118. Returns:
  119. `np.ndarray`: The resized image.
  120. """
  121. size = get_size_dict(size)
  122. if "height" not in size or "width" not in size:
  123. raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
  124. output_size = (size["height"], size["width"])
  125. return resize(
  126. image,
  127. size=output_size,
  128. resample=resample,
  129. data_format=data_format,
  130. input_data_format=input_data_format,
  131. **kwargs,
  132. )
  133. @filter_out_non_signature_kwargs()
  134. def preprocess(
  135. self,
  136. images: ImageInput,
  137. do_resize: Optional[bool] = None,
  138. size: Dict[str, int] = None,
  139. resample: PILImageResampling = None,
  140. do_rescale: Optional[bool] = None,
  141. rescale_factor: Optional[float] = None,
  142. do_normalize: Optional[bool] = None,
  143. image_mean: Optional[Union[float, List[float]]] = None,
  144. image_std: Optional[Union[float, List[float]]] = None,
  145. return_tensors: Optional[Union[str, TensorType]] = None,
  146. data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,
  147. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  148. ):
  149. """
  150. Preprocess an image or batch of images.
  151. Args:
  152. images (`ImageInput`):
  153. Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
  154. passing in images with pixel values between 0 and 1, set `do_rescale=False`.
  155. do_resize (`bool`, *optional*, defaults to `self.do_resize`):
  156. Whether to resize the image.
  157. size (`Dict[str, int]`, *optional*, defaults to `self.size`):
  158. Dictionary in the format `{"height": h, "width": w}` specifying the size of the output image after
  159. resizing.
  160. resample (`PILImageResampling` filter, *optional*, defaults to `self.resample`):
  161. `PILImageResampling` filter to use if resizing the image e.g. `PILImageResampling.BILINEAR`. Only has
  162. an effect if `do_resize` is set to `True`.
  163. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
  164. Whether to rescale the image values between [0 - 1].
  165. rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
  166. Rescale factor to rescale the image by if `do_rescale` is set to `True`.
  167. do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
  168. Whether to normalize the image.
  169. image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
  170. Image mean to use if `do_normalize` is set to `True`.
  171. image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
  172. Image standard deviation to use if `do_normalize` is set to `True`.
  173. return_tensors (`str` or `TensorType`, *optional*):
  174. The type of tensors to return. Can be one of:
  175. - Unset: Return a list of `np.ndarray`.
  176. - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
  177. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
  178. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
  179. - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
  180. data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
  181. The channel dimension format for the output image. Can be one of:
  182. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  183. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  184. - Unset: Use the channel dimension format of the input image.
  185. input_data_format (`ChannelDimension` or `str`, *optional*):
  186. The channel dimension format for the input image. If unset, the channel dimension format is inferred
  187. from the input image. Can be one of:
  188. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  189. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  190. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  191. """
  192. do_resize = do_resize if do_resize is not None else self.do_resize
  193. do_rescale = do_rescale if do_rescale is not None else self.do_rescale
  194. do_normalize = do_normalize if do_normalize is not None else self.do_normalize
  195. resample = resample if resample is not None else self.resample
  196. rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
  197. image_mean = image_mean if image_mean is not None else self.image_mean
  198. image_std = image_std if image_std is not None else self.image_std
  199. size = size if size is not None else self.size
  200. size_dict = get_size_dict(size)
  201. images = make_list_of_images(images)
  202. if not valid_images(images):
  203. raise ValueError(
  204. "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
  205. "torch.Tensor, tf.Tensor or jax.ndarray."
  206. )
  207. validate_preprocess_arguments(
  208. do_rescale=do_rescale,
  209. rescale_factor=rescale_factor,
  210. do_normalize=do_normalize,
  211. image_mean=image_mean,
  212. image_std=image_std,
  213. do_resize=do_resize,
  214. size=size,
  215. resample=resample,
  216. )
  217. # All transformations expect numpy arrays.
  218. images = [to_numpy_array(image) for image in images]
  219. if is_scaled_image(images[0]) and do_rescale:
  220. logger.warning_once(
  221. "It looks like you are trying to rescale already rescaled images. If the input"
  222. " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
  223. )
  224. if input_data_format is None:
  225. # We assume that all images have the same channel dimension format.
  226. input_data_format = infer_channel_dimension_format(images[0])
  227. if do_resize:
  228. images = [
  229. self.resize(image=image, size=size_dict, resample=resample, input_data_format=input_data_format)
  230. for image in images
  231. ]
  232. if do_rescale:
  233. images = [
  234. self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
  235. for image in images
  236. ]
  237. if do_normalize:
  238. images = [
  239. self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
  240. for image in images
  241. ]
  242. images = [
  243. to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
  244. ]
  245. data = {"pixel_values": images}
  246. return BatchFeature(data=data, tensor_type=return_tensors)