image_processing_pvt.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. # coding=utf-8
  2. # Copyright 2023 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 Pvt."""
  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_DEFAULT_MEAN,
  22. IMAGENET_DEFAULT_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 PvtImageProcessor(BaseImageProcessor):
  36. r"""
  37. Constructs a PVT 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_DEFAULT_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_DEFAULT_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_DEFAULT_MEAN
  87. self.image_std = image_std if image_std is not None else IMAGENET_DEFAULT_STD
  88. # Copied from transformers.models.vit.image_processing_vit.ViTImageProcessor.resize
  89. def resize(
  90. self,
  91. image: np.ndarray,
  92. size: Dict[str, int],
  93. resample: PILImageResampling = PILImageResampling.BILINEAR,
  94. data_format: Optional[Union[str, ChannelDimension]] = None,
  95. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  96. **kwargs,
  97. ) -> np.ndarray:
  98. """
  99. Resize an image to `(size["height"], size["width"])`.
  100. Args:
  101. image (`np.ndarray`):
  102. Image to resize.
  103. size (`Dict[str, int]`):
  104. Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
  105. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
  106. `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
  107. data_format (`ChannelDimension` or `str`, *optional*):
  108. The channel dimension format for the output image. If unset, the channel dimension format of the input
  109. image is used. Can be one of:
  110. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  111. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  112. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  113. input_data_format (`ChannelDimension` or `str`, *optional*):
  114. The channel dimension format for the input image. If unset, the channel dimension format is inferred
  115. from the input image. Can be one of:
  116. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  117. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  118. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  119. Returns:
  120. `np.ndarray`: The resized image.
  121. """
  122. size = get_size_dict(size)
  123. if "height" not in size or "width" not in size:
  124. raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
  125. output_size = (size["height"], size["width"])
  126. return resize(
  127. image,
  128. size=output_size,
  129. resample=resample,
  130. data_format=data_format,
  131. input_data_format=input_data_format,
  132. **kwargs,
  133. )
  134. @filter_out_non_signature_kwargs()
  135. def preprocess(
  136. self,
  137. images: ImageInput,
  138. do_resize: Optional[bool] = None,
  139. size: Dict[str, int] = None,
  140. resample: PILImageResampling = None,
  141. do_rescale: Optional[bool] = None,
  142. rescale_factor: Optional[float] = None,
  143. do_normalize: Optional[bool] = None,
  144. image_mean: Optional[Union[float, List[float]]] = None,
  145. image_std: Optional[Union[float, List[float]]] = None,
  146. return_tensors: Optional[Union[str, TensorType]] = None,
  147. data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,
  148. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  149. ):
  150. """
  151. Preprocess an image or batch of images.
  152. Args:
  153. images (`ImageInput`):
  154. Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
  155. passing in images with pixel values between 0 and 1, set `do_rescale=False`.
  156. do_resize (`bool`, *optional*, defaults to `self.do_resize`):
  157. Whether to resize the image.
  158. size (`Dict[str, int]`, *optional*, defaults to `self.size`):
  159. Dictionary in the format `{"height": h, "width": w}` specifying the size of the output image after
  160. resizing.
  161. resample (`PILImageResampling` filter, *optional*, defaults to `self.resample`):
  162. `PILImageResampling` filter to use if resizing the image e.g. `PILImageResampling.BILINEAR`. Only has
  163. an effect if `do_resize` is set to `True`.
  164. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
  165. Whether to rescale the image values between [0 - 1].
  166. rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
  167. Rescale factor to rescale the image by if `do_rescale` is set to `True`.
  168. do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
  169. Whether to normalize the image.
  170. image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
  171. Image mean to use if `do_normalize` is set to `True`.
  172. image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
  173. Image standard deviation to use if `do_normalize` is set to `True`.
  174. return_tensors (`str` or `TensorType`, *optional*):
  175. The type of tensors to return. Can be one of:
  176. - Unset: Return a list of `np.ndarray`.
  177. - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
  178. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
  179. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
  180. - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
  181. data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
  182. The channel dimension format for the output image. Can be one of:
  183. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  184. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  185. - Unset: Use the channel dimension format of the input image.
  186. input_data_format (`ChannelDimension` or `str`, *optional*):
  187. The channel dimension format for the input image. If unset, the channel dimension format is inferred
  188. from the input image. Can be one of:
  189. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  190. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  191. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  192. """
  193. do_resize = do_resize if do_resize is not None else self.do_resize
  194. do_rescale = do_rescale if do_rescale is not None else self.do_rescale
  195. do_normalize = do_normalize if do_normalize is not None else self.do_normalize
  196. resample = resample if resample is not None else self.resample
  197. rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
  198. image_mean = image_mean if image_mean is not None else self.image_mean
  199. image_std = image_std if image_std is not None else self.image_std
  200. size = size if size is not None else self.size
  201. size_dict = get_size_dict(size)
  202. images = make_list_of_images(images)
  203. if not valid_images(images):
  204. raise ValueError(
  205. "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
  206. "torch.Tensor, tf.Tensor or jax.ndarray."
  207. )
  208. validate_preprocess_arguments(
  209. do_rescale=do_rescale,
  210. rescale_factor=rescale_factor,
  211. do_normalize=do_normalize,
  212. image_mean=image_mean,
  213. image_std=image_std,
  214. do_resize=do_resize,
  215. size=size,
  216. resample=resample,
  217. )
  218. # All transformations expect numpy arrays.
  219. images = [to_numpy_array(image) for image in images]
  220. if is_scaled_image(images[0]) and do_rescale:
  221. logger.warning_once(
  222. "It looks like you are trying to rescale already rescaled images. If the input"
  223. " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
  224. )
  225. if input_data_format is None:
  226. # We assume that all images have the same channel dimension format.
  227. input_data_format = infer_channel_dimension_format(images[0])
  228. if do_resize:
  229. images = [
  230. self.resize(image=image, size=size_dict, resample=resample, input_data_format=input_data_format)
  231. for image in images
  232. ]
  233. if do_rescale:
  234. images = [
  235. self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
  236. for image in images
  237. ]
  238. if do_normalize:
  239. images = [
  240. self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
  241. for image in images
  242. ]
  243. images = [
  244. to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
  245. ]
  246. data = {"pixel_values": images}
  247. return BatchFeature(data=data, tensor_type=return_tensors)