image_processing_deit.py 15 KB

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