image_processing_convnext.py 15 KB

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