image_processing_bit.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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 BiT."""
  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. convert_to_rgb,
  21. get_resize_output_image_size,
  22. resize,
  23. to_channel_dimension_format,
  24. )
  25. from ...image_utils import (
  26. OPENAI_CLIP_MEAN,
  27. OPENAI_CLIP_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. logger = logging.get_logger(__name__)
  40. if is_vision_available():
  41. import PIL
  42. class BitImageProcessor(BaseImageProcessor):
  43. r"""
  44. Constructs a BiT image processor.
  45. Args:
  46. do_resize (`bool`, *optional*, defaults to `True`):
  47. Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
  48. `do_resize` in the `preprocess` method.
  49. size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
  50. Size of the image after resizing. The shortest edge of the image is resized to size["shortest_edge"], with
  51. the longest edge resized to keep the input aspect ratio. Can be overridden by `size` in the `preprocess`
  52. method.
  53. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
  54. Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
  55. do_center_crop (`bool`, *optional*, defaults to `True`):
  56. Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the
  57. `preprocess` method.
  58. crop_size (`Dict[str, int]` *optional*, defaults to 224):
  59. Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess`
  60. method.
  61. do_rescale (`bool`, *optional*, defaults to `True`):
  62. Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
  63. 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 `rescale_factor` in the `preprocess`
  66. method.
  67. do_normalize:
  68. Whether to normalize the image. Can be overridden by `do_normalize` in the `preprocess` method.
  69. image_mean (`float` or `List[float]`, *optional*, defaults to `OPENAI_CLIP_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 `OPENAI_CLIP_MEAN`):
  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. Can be overridden by the `image_std` parameter in the `preprocess` method.
  76. do_convert_rgb (`bool`, *optional*, defaults to `True`):
  77. Whether to convert the image to RGB.
  78. """
  79. model_input_names = ["pixel_values"]
  80. def __init__(
  81. self,
  82. do_resize: bool = True,
  83. size: Dict[str, int] = None,
  84. resample: PILImageResampling = PILImageResampling.BICUBIC,
  85. do_center_crop: bool = True,
  86. crop_size: Dict[str, int] = None,
  87. do_rescale: bool = True,
  88. rescale_factor: Union[int, float] = 1 / 255,
  89. do_normalize: bool = True,
  90. image_mean: Optional[Union[float, List[float]]] = None,
  91. image_std: Optional[Union[float, List[float]]] = None,
  92. do_convert_rgb: bool = True,
  93. **kwargs,
  94. ) -> None:
  95. super().__init__(**kwargs)
  96. size = size if size is not None else {"shortest_edge": 224}
  97. size = get_size_dict(size, default_to_square=False)
  98. crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
  99. crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
  100. self.do_resize = do_resize
  101. self.size = size
  102. self.resample = resample
  103. self.do_center_crop = do_center_crop
  104. self.crop_size = crop_size
  105. self.do_rescale = do_rescale
  106. self.rescale_factor = rescale_factor
  107. self.do_normalize = do_normalize
  108. self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
  109. self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
  110. self.do_convert_rgb = do_convert_rgb
  111. # Copied from transformers.models.clip.image_processing_clip.CLIPImageProcessor.resize
  112. def resize(
  113. self,
  114. image: np.ndarray,
  115. size: Dict[str, int],
  116. resample: PILImageResampling = PILImageResampling.BICUBIC,
  117. data_format: Optional[Union[str, ChannelDimension]] = None,
  118. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  119. **kwargs,
  120. ) -> np.ndarray:
  121. """
  122. Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge
  123. resized to keep the input aspect ratio.
  124. Args:
  125. image (`np.ndarray`):
  126. Image to resize.
  127. size (`Dict[str, int]`):
  128. Size of the output image.
  129. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
  130. Resampling filter to use when resiizing the image.
  131. data_format (`str` or `ChannelDimension`, *optional*):
  132. The channel dimension format of the image. If not provided, it will be the same as the input image.
  133. input_data_format (`ChannelDimension` or `str`, *optional*):
  134. The channel dimension format of the input image. If not provided, it will be inferred.
  135. """
  136. default_to_square = True
  137. if "shortest_edge" in size:
  138. size = size["shortest_edge"]
  139. default_to_square = False
  140. elif "height" in size and "width" in size:
  141. size = (size["height"], size["width"])
  142. else:
  143. raise ValueError("Size must contain either 'shortest_edge' or 'height' and 'width'.")
  144. output_size = get_resize_output_image_size(
  145. image,
  146. size=size,
  147. default_to_square=default_to_square,
  148. input_data_format=input_data_format,
  149. )
  150. return resize(
  151. image,
  152. size=output_size,
  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: bool = None,
  163. size: Dict[str, int] = None,
  164. resample: PILImageResampling = None,
  165. do_center_crop: bool = None,
  166. crop_size: int = None,
  167. do_rescale: bool = None,
  168. rescale_factor: float = None,
  169. do_normalize: bool = None,
  170. image_mean: Optional[Union[float, List[float]]] = None,
  171. image_std: Optional[Union[float, List[float]]] = None,
  172. do_convert_rgb: bool = None,
  173. return_tensors: Optional[Union[str, TensorType]] = None,
  174. data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
  175. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  176. ) -> PIL.Image.Image:
  177. """
  178. Preprocess an image or batch of images.
  179. Args:
  180. images (`ImageInput`):
  181. Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
  182. passing in images with pixel values between 0 and 1, set `do_rescale=False`.
  183. do_resize (`bool`, *optional*, defaults to `self.do_resize`):
  184. Whether to resize the image.
  185. size (`Dict[str, int]`, *optional*, defaults to `self.size`):
  186. Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
  187. the longest edge resized to keep the input aspect ratio.
  188. resample (`int`, *optional*, defaults to `self.resample`):
  189. Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
  190. has an effect if `do_resize` is set to `True`.
  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 center crop. Only has an effect if `do_center_crop` is set to `True`.
  195. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
  196. Whether to rescale the image.
  197. rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
  198. Rescale factor to rescale the image by if `do_rescale` is set to `True`.
  199. do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
  200. Whether to normalize the image.
  201. image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
  202. Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
  203. image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
  204. Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
  205. `True`.
  206. do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
  207. Whether to convert the image to RGB.
  208. return_tensors (`str` or `TensorType`, *optional*):
  209. The type of tensors to return. Can be one of:
  210. - Unset: Return a list of `np.ndarray`.
  211. - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
  212. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
  213. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
  214. - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
  215. data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
  216. The channel dimension format for the output image. Can be one of:
  217. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  218. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  219. - Unset: Use the channel dimension format of the input image.
  220. input_data_format (`ChannelDimension` or `str`, *optional*):
  221. The channel dimension format for the input image. If unset, the channel dimension format is inferred
  222. from the input 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. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  226. """
  227. do_resize = do_resize if do_resize is not None else self.do_resize
  228. size = size if size is not None else self.size
  229. size = get_size_dict(size, param_name="size", default_to_square=False)
  230. resample = resample if resample is not None else self.resample
  231. do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
  232. crop_size = crop_size if crop_size is not None else self.crop_size
  233. crop_size = get_size_dict(crop_size, param_name="crop_size", default_to_square=True)
  234. do_rescale = do_rescale if do_rescale is not None else self.do_rescale
  235. rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
  236. do_normalize = do_normalize if do_normalize is not None else self.do_normalize
  237. image_mean = image_mean if image_mean is not None else self.image_mean
  238. image_std = image_std if image_std is not None else self.image_std
  239. do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
  240. images = make_list_of_images(images)
  241. if not valid_images(images):
  242. raise ValueError(
  243. "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
  244. "torch.Tensor, tf.Tensor or jax.ndarray."
  245. )
  246. validate_preprocess_arguments(
  247. do_rescale=do_rescale,
  248. rescale_factor=rescale_factor,
  249. do_normalize=do_normalize,
  250. image_mean=image_mean,
  251. image_std=image_std,
  252. do_center_crop=do_center_crop,
  253. crop_size=crop_size,
  254. do_resize=do_resize,
  255. size=size,
  256. resample=resample,
  257. )
  258. # PIL RGBA images are converted to RGB
  259. if do_convert_rgb:
  260. images = [convert_to_rgb(image) for image in images]
  261. # All transformations expect numpy arrays.
  262. images = [to_numpy_array(image) for image in images]
  263. if is_scaled_image(images[0]) and do_rescale:
  264. logger.warning_once(
  265. "It looks like you are trying to rescale already rescaled images. If the input"
  266. " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
  267. )
  268. if input_data_format is None:
  269. # We assume that all images have the same channel dimension format.
  270. input_data_format = infer_channel_dimension_format(images[0])
  271. all_images = []
  272. for image in images:
  273. if do_resize:
  274. image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
  275. if do_center_crop:
  276. image = self.center_crop(image=image, size=crop_size, input_data_format=input_data_format)
  277. if do_rescale:
  278. image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
  279. if do_normalize:
  280. image = self.normalize(
  281. image=image, mean=image_mean, std=image_std, input_data_format=input_data_format
  282. )
  283. all_images.append(image)
  284. images = [
  285. to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
  286. for image in all_images
  287. ]
  288. data = {"pixel_values": images}
  289. return BatchFeature(data=data, tensor_type=return_tensors)