image_processing_efficientnet.py 18 KB

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