image_processing_perceiver.py 17 KB

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