image_processing_levit.py 16 KB

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