image_processing_blip.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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 BLIP."""
  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 convert_to_rgb, resize, to_channel_dimension_format
  20. from ...image_utils import (
  21. OPENAI_CLIP_MEAN,
  22. OPENAI_CLIP_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 BlipImageProcessor(BaseImageProcessor):
  38. r"""
  39. Constructs a BLIP 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 the
  43. `do_resize` parameter in the `preprocess` method.
  44. size (`dict`, *optional*, defaults to `{"height": 384, "width": 384}`):
  45. Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess`
  46. method.
  47. resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
  48. Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`. Can be
  49. overridden by the `resample` parameter in the `preprocess` method.
  50. do_rescale (`bool`, *optional*, defaults to `True`):
  51. Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the
  52. `do_rescale` parameter in the `preprocess` method.
  53. rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
  54. Scale factor to use if rescaling the image. Only has an effect if `do_rescale` is set to `True`. Can be
  55. overridden by the `rescale_factor` parameter in the `preprocess` method.
  56. do_normalize (`bool`, *optional*, defaults to `True`):
  57. Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
  58. method. Can be overridden by the `do_normalize` parameter in the `preprocess` method.
  59. image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
  60. Mean to use if normalizing the image. This is a float or list of floats the length of the number of
  61. channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be
  62. overridden by the `image_mean` parameter in the `preprocess` method.
  63. image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
  64. Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
  65. number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
  66. Can be overridden by the `image_std` parameter in the `preprocess` method.
  67. do_convert_rgb (`bool`, *optional*, defaults to `True`):
  68. Whether to convert the image to RGB.
  69. """
  70. model_input_names = ["pixel_values"]
  71. def __init__(
  72. self,
  73. do_resize: bool = True,
  74. size: Dict[str, int] = None,
  75. resample: PILImageResampling = PILImageResampling.BICUBIC,
  76. do_rescale: bool = True,
  77. rescale_factor: Union[int, float] = 1 / 255,
  78. do_normalize: bool = True,
  79. image_mean: Optional[Union[float, List[float]]] = None,
  80. image_std: Optional[Union[float, List[float]]] = None,
  81. do_convert_rgb: bool = True,
  82. **kwargs,
  83. ) -> None:
  84. super().__init__(**kwargs)
  85. size = size if size is not None else {"height": 384, "width": 384}
  86. size = get_size_dict(size, default_to_square=True)
  87. self.do_resize = do_resize
  88. self.size = size
  89. self.resample = resample
  90. self.do_rescale = do_rescale
  91. self.rescale_factor = rescale_factor
  92. self.do_normalize = do_normalize
  93. self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
  94. self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
  95. self.do_convert_rgb = do_convert_rgb
  96. # Copied from transformers.models.vit.image_processing_vit.ViTImageProcessor.resize with PILImageResampling.BILINEAR->PILImageResampling.BICUBIC
  97. def resize(
  98. self,
  99. image: np.ndarray,
  100. size: Dict[str, int],
  101. resample: PILImageResampling = PILImageResampling.BICUBIC,
  102. data_format: Optional[Union[str, ChannelDimension]] = None,
  103. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  104. **kwargs,
  105. ) -> np.ndarray:
  106. """
  107. Resize an image to `(size["height"], size["width"])`.
  108. Args:
  109. image (`np.ndarray`):
  110. Image to resize.
  111. size (`Dict[str, int]`):
  112. Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
  113. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
  114. `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BICUBIC`.
  115. data_format (`ChannelDimension` or `str`, *optional*):
  116. The channel dimension format for the output image. If unset, the channel dimension format of the input
  117. image is used. Can be one of:
  118. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  119. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  120. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  121. input_data_format (`ChannelDimension` or `str`, *optional*):
  122. The channel dimension format for the input image. If unset, the channel dimension format is inferred
  123. from the input image. Can be one of:
  124. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  125. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  126. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  127. Returns:
  128. `np.ndarray`: The resized image.
  129. """
  130. size = get_size_dict(size)
  131. if "height" not in size or "width" not in size:
  132. raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
  133. output_size = (size["height"], size["width"])
  134. return resize(
  135. image,
  136. size=output_size,
  137. resample=resample,
  138. data_format=data_format,
  139. input_data_format=input_data_format,
  140. **kwargs,
  141. )
  142. @filter_out_non_signature_kwargs()
  143. def preprocess(
  144. self,
  145. images: ImageInput,
  146. do_resize: Optional[bool] = None,
  147. size: Optional[Dict[str, int]] = None,
  148. resample: PILImageResampling = None,
  149. do_rescale: Optional[bool] = None,
  150. rescale_factor: Optional[float] = None,
  151. do_normalize: Optional[bool] = None,
  152. image_mean: Optional[Union[float, List[float]]] = None,
  153. image_std: Optional[Union[float, List[float]]] = None,
  154. return_tensors: Optional[Union[str, TensorType]] = None,
  155. do_convert_rgb: bool = None,
  156. data_format: ChannelDimension = ChannelDimension.FIRST,
  157. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  158. ) -> PIL.Image.Image:
  159. """
  160. Preprocess an image or batch of images.
  161. Args:
  162. images (`ImageInput`):
  163. Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
  164. passing in images with pixel values between 0 and 1, set `do_rescale=False`.
  165. do_resize (`bool`, *optional*, defaults to `self.do_resize`):
  166. Whether to resize the image.
  167. size (`Dict[str, int]`, *optional*, defaults to `self.size`):
  168. Controls the size of the image after `resize`. The shortest edge of the image is resized to
  169. `size["shortest_edge"]` whilst preserving the aspect ratio. If the longest edge of this resized image
  170. is > `int(size["shortest_edge"] * (1333 / 800))`, then the image is resized again to make the longest
  171. edge equal to `int(size["shortest_edge"] * (1333 / 800))`.
  172. resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
  173. Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`.
  174. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
  175. Whether to rescale the image values between [0 - 1].
  176. rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
  177. Rescale factor to rescale the image by if `do_rescale` is set to `True`.
  178. do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
  179. Whether to normalize the image.
  180. image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
  181. Image mean to normalize the image by if `do_normalize` is set to `True`.
  182. image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
  183. Image standard deviation to normalize the image by if `do_normalize` is set to `True`.
  184. do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
  185. Whether to convert the image to RGB.
  186. return_tensors (`str` or `TensorType`, *optional*):
  187. The type of tensors to return. Can be one of:
  188. - Unset: Return a list of `np.ndarray`.
  189. - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
  190. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
  191. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
  192. - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
  193. data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
  194. The channel dimension format for the output image. Can be one of:
  195. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  196. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  197. - Unset: Use the channel dimension format of the input image.
  198. input_data_format (`ChannelDimension` or `str`, *optional*):
  199. The channel dimension format for the input image. If unset, the channel dimension format is inferred
  200. from the input image. Can be one of:
  201. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  202. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  203. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  204. """
  205. do_resize = do_resize if do_resize is not None else self.do_resize
  206. resample = resample if resample is not None else self.resample
  207. do_rescale = do_rescale if do_rescale is not None else self.do_rescale
  208. rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
  209. do_normalize = do_normalize if do_normalize is not None else self.do_normalize
  210. image_mean = image_mean if image_mean is not None else self.image_mean
  211. image_std = image_std if image_std is not None else self.image_std
  212. do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
  213. size = size if size is not None else self.size
  214. size = get_size_dict(size, default_to_square=False)
  215. images = make_list_of_images(images)
  216. if not valid_images(images):
  217. raise ValueError(
  218. "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
  219. "torch.Tensor, tf.Tensor or jax.ndarray."
  220. )
  221. validate_preprocess_arguments(
  222. do_rescale=do_rescale,
  223. rescale_factor=rescale_factor,
  224. do_normalize=do_normalize,
  225. image_mean=image_mean,
  226. image_std=image_std,
  227. do_resize=do_resize,
  228. size=size,
  229. resample=resample,
  230. )
  231. # PIL RGBA images are converted to RGB
  232. if do_convert_rgb:
  233. images = [convert_to_rgb(image) for image in images]
  234. # All transformations expect numpy arrays.
  235. images = [to_numpy_array(image) for image in images]
  236. if is_scaled_image(images[0]) and do_rescale:
  237. logger.warning_once(
  238. "It looks like you are trying to rescale already rescaled images. If the input"
  239. " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
  240. )
  241. if input_data_format is None:
  242. # We assume that all images have the same channel dimension format.
  243. input_data_format = infer_channel_dimension_format(images[0])
  244. if do_resize:
  245. images = [
  246. self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
  247. for image in images
  248. ]
  249. if do_rescale:
  250. images = [
  251. self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
  252. for image in images
  253. ]
  254. if do_normalize:
  255. images = [
  256. self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
  257. for image in images
  258. ]
  259. images = [
  260. to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
  261. ]
  262. encoded_outputs = BatchFeature(data={"pixel_values": images}, tensor_type=return_tensors)
  263. return encoded_outputs