image_processing_idefics2.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. # coding=utf-8
  2. # Copyright 2024 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. from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
  16. import numpy as np
  17. from ...image_processing_utils import BaseImageProcessor, BatchFeature
  18. from ...image_transforms import PaddingMode, pad, resize, to_channel_dimension_format
  19. from ...image_utils import (
  20. IMAGENET_STANDARD_MEAN,
  21. IMAGENET_STANDARD_STD,
  22. ChannelDimension,
  23. ImageInput,
  24. PILImageResampling,
  25. get_image_size,
  26. infer_channel_dimension_format,
  27. is_scaled_image,
  28. is_valid_image,
  29. to_numpy_array,
  30. valid_images,
  31. validate_preprocess_arguments,
  32. )
  33. from ...utils import TensorType, is_vision_available, logging
  34. logger = logging.get_logger(__name__)
  35. if is_vision_available():
  36. import PIL
  37. from PIL import Image
  38. def get_resize_output_image_size(image, size, input_data_format) -> Tuple[int, int]:
  39. """
  40. Get the output size of the image after resizing given a dictionary specifying the max and min sizes.
  41. Args:
  42. image (`np.ndarray`):
  43. Image to resize.
  44. size (`Dict[str, int]`):
  45. Size of the output image containing the keys "shortest_edge" and "longest_edge".
  46. input_data_format (`ChannelDimension` or `str`):
  47. The channel dimension format of the input image.
  48. Returns:
  49. The output size of the image after resizing.
  50. """
  51. height, width = get_image_size(image, channel_dim=input_data_format)
  52. min_len = size["shortest_edge"]
  53. max_len = size["longest_edge"]
  54. aspect_ratio = width / height
  55. if width >= height and width > max_len:
  56. width = max_len
  57. height = int(width / aspect_ratio)
  58. elif height > width and height > max_len:
  59. height = max_len
  60. width = int(height * aspect_ratio)
  61. height = max(height, min_len)
  62. width = max(width, min_len)
  63. return height, width
  64. def make_list_of_images(images: ImageInput) -> List[List[np.ndarray]]:
  65. """
  66. Convert a single image or a list of images to a list of numpy arrays.
  67. Args:
  68. images (`ImageInput`):
  69. A single image or a list of images.
  70. Returns:
  71. A list of numpy arrays.
  72. """
  73. # If it's a single image, convert it to a list of lists
  74. if is_valid_image(images):
  75. images = [[images]]
  76. # If it's a list of images, it's a single batch, so convert it to a list of lists
  77. elif isinstance(images, (list, tuple)) and len(images) > 0 and is_valid_image(images[0]):
  78. images = [images]
  79. # If it's a list of batches, it's already in the right format
  80. elif (
  81. isinstance(images, (list, tuple))
  82. and len(images) > 0
  83. and isinstance(images[0], (list, tuple))
  84. and is_valid_image(images[0][0])
  85. ):
  86. pass
  87. else:
  88. raise ValueError(
  89. "Invalid input type. Must be a single image, a list of images, or a list of batches of images."
  90. )
  91. return images
  92. # Copied from transformers.models.detr.image_processing_detr.max_across_indices
  93. def max_across_indices(values: Iterable[Any]) -> List[Any]:
  94. """
  95. Return the maximum value across all indices of an iterable of values.
  96. """
  97. return [max(values_i) for values_i in zip(*values)]
  98. def get_max_height_width(
  99. images_list: List[List[np.ndarray]], input_data_format: Optional[Union[str, ChannelDimension]] = None
  100. ) -> List[int]:
  101. """
  102. Get the maximum height and width across all images in a batch.
  103. """
  104. if input_data_format is None:
  105. input_data_format = infer_channel_dimension_format(images_list[0][0])
  106. image_sizes = []
  107. for images in images_list:
  108. for image in images:
  109. image_sizes.append(get_image_size(image, channel_dim=input_data_format))
  110. max_height, max_width = max_across_indices(image_sizes)
  111. return (max_height, max_width)
  112. # Copied from transformers.models.detr.image_processing_detr.make_pixel_mask
  113. def make_pixel_mask(
  114. image: np.ndarray, output_size: Tuple[int, int], input_data_format: Optional[Union[str, ChannelDimension]] = None
  115. ) -> np.ndarray:
  116. """
  117. Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
  118. Args:
  119. image (`np.ndarray`):
  120. Image to make the pixel mask for.
  121. output_size (`Tuple[int, int]`):
  122. Output size of the mask.
  123. """
  124. input_height, input_width = get_image_size(image, channel_dim=input_data_format)
  125. mask = np.zeros(output_size, dtype=np.int64)
  126. mask[:input_height, :input_width] = 1
  127. return mask
  128. # FIXME Amy: merge this function with the one in image_transforms.py
  129. def convert_to_rgb(image: ImageInput) -> ImageInput:
  130. """
  131. Converts an image to RGB format. Only converts if the image is of type PIL.Image.Image, otherwise returns the image
  132. as is.
  133. Args:
  134. image (Image):
  135. The image to convert.
  136. """
  137. if not isinstance(image, PIL.Image.Image):
  138. return image
  139. # `image.convert("RGB")` would only work for .jpg images, as it creates a wrong background
  140. # for transparent images. The call to `alpha_composite` handles this case
  141. if image.mode == "RGB":
  142. return image
  143. image_rgba = image.convert("RGBA")
  144. background = Image.new("RGBA", image_rgba.size, (255, 255, 255))
  145. alpha_composite = Image.alpha_composite(background, image_rgba)
  146. alpha_composite = alpha_composite.convert("RGB")
  147. return alpha_composite
  148. class Idefics2ImageProcessor(BaseImageProcessor):
  149. r"""
  150. Constructs a Idefics image processor.
  151. Args:
  152. do_convert_rgb (`bool`, *optional*, defaults to `True`):
  153. Whether to convert the image to RGB. This is useful if the input image is of a different format e.g. RGBA.
  154. Only has an effect if the input image is in the PIL format.
  155. do_resize (`bool`, *optional*, defaults to `True`):
  156. Whether to resize the image. The longest edge of the image is resized to be <= `size["longest_edge"]`, with the
  157. shortest edge resized to keep the input aspect ratio, with a minimum size of `size["shortest_edge"]`.
  158. size (`Dict`, *optional*):
  159. Controls the size of the output image. This is a dictionary containing the keys "shortest_edge" and "longest_edge".
  160. resample (`Resampling`, *optional*, defaults to `Resampling.BILINEAR`):
  161. Resampling filter to use when resizing the image.
  162. do_rescale (`bool`, *optional*, defaults to `True`):
  163. Whether to rescale the image. If set to `True`, the image is rescaled to have pixel values between 0 and 1.
  164. rescale_factor (`float`, *optional*, defaults to `1/255`):
  165. Rescale factor to rescale the image by if `do_rescale` is set to `True`.
  166. do_normalize (`bool`, *optional*, defaults to `True`):
  167. Whether to normalize the image. If set to `True`, the image is normalized to have a mean of `image_mean` and
  168. a standard deviation of `image_std`.
  169. image_mean (`float` or `List[float]`, *optional*, defaults to `IDEFICS_STANDARD_MEAN`):
  170. Mean to use if normalizing the image. This is a float or list of floats the length of the number of
  171. channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be
  172. overridden by the `image_mean` parameter in the `preprocess` method.
  173. image_std (`float` or `List[float]`, *optional*, defaults to `IDEFICS_STANDARD_STD`):
  174. Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
  175. number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
  176. Can be overridden by the `image_std` parameter in the `preprocess` method.
  177. do_pad (`bool`, *optional*, defaults to `True`):
  178. Whether or not to pad the images to the largest height and width in the batch and number of images per
  179. sample in the batch, such that the returned tensor is of shape (batch_size, max_num_images, num_channels, max_height, max_width).
  180. do_image_splitting (`bool`, *optional*, defaults to `False`):
  181. Whether to split the image into a sequence 4 equal sub-images concatenated with the original image. That
  182. strategy was first introduced in https://arxiv.org/abs/2311.06607.
  183. """
  184. model_input_names = ["pixel_values"]
  185. def __init__(
  186. self,
  187. do_convert_rgb: bool = True,
  188. do_resize: bool = True,
  189. size: Dict[str, int] = None,
  190. resample: PILImageResampling = PILImageResampling.BILINEAR,
  191. do_rescale: bool = True,
  192. rescale_factor: float = 1 / 255,
  193. do_normalize: bool = True,
  194. image_mean: Optional[Union[float, List[float]]] = None,
  195. image_std: Optional[Union[float, List[float]]] = None,
  196. do_pad: bool = True,
  197. do_image_splitting: bool = False,
  198. **kwargs,
  199. ) -> None:
  200. super().__init__(**kwargs)
  201. self.do_convert_rgb = do_convert_rgb
  202. self.do_resize = do_resize
  203. self.size = size if size is not None else {"shortest_edge": 378, "longest_edge": 980}
  204. self.resample = resample
  205. self.do_rescale = do_rescale
  206. self.rescale_factor = rescale_factor
  207. self.do_normalize = do_normalize
  208. self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
  209. self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
  210. self.do_pad = do_pad
  211. self.do_image_splitting = do_image_splitting
  212. def resize(
  213. self,
  214. image: np.ndarray,
  215. size: Dict[str, int],
  216. resample: PILImageResampling = PILImageResampling.BILINEAR,
  217. data_format: Optional[Union[str, ChannelDimension]] = None,
  218. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  219. **kwargs,
  220. ) -> np.ndarray:
  221. """
  222. Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge
  223. resized to keep the input aspect ratio.
  224. Args:
  225. image (`np.ndarray`):
  226. Image to resize.
  227. size (`Dict[str, int]`):
  228. Size of the output image.
  229. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
  230. Resampling filter to use when resiizing the image.
  231. data_format (`str` or `ChannelDimension`, *optional*):
  232. The channel dimension format of the image. If not provided, it will be the same as the input image.
  233. input_data_format (`ChannelDimension` or `str`, *optional*):
  234. The channel dimension format of the input image. If not provided, it will be inferred.
  235. """
  236. if "shortest_edge" in size and "longest_edge" in size:
  237. size = get_resize_output_image_size(image, size, input_data_format)
  238. elif "height" in size and "width" in size:
  239. size = (size["height"], size["width"])
  240. else:
  241. raise ValueError(
  242. "size must be a dictionary with keys 'shortest_edge' and 'longest_edge' or 'height' and 'width'."
  243. )
  244. return resize(
  245. image, size, resample=resample, data_format=data_format, input_data_format=input_data_format, **kwargs
  246. )
  247. # Copied from transformers.models.vilt.image_processing_vilt.ViltImageProcessor._pad_image
  248. def _pad_image(
  249. self,
  250. image: np.ndarray,
  251. output_size: Tuple[int, int],
  252. constant_values: Union[float, Iterable[float]] = 0,
  253. data_format: Optional[ChannelDimension] = None,
  254. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  255. ) -> np.ndarray:
  256. """
  257. Pad an image with zeros to the given size.
  258. """
  259. input_height, input_width = get_image_size(image, channel_dim=input_data_format)
  260. output_height, output_width = output_size
  261. pad_bottom = output_height - input_height
  262. pad_right = output_width - input_width
  263. padding = ((0, pad_bottom), (0, pad_right))
  264. padded_image = pad(
  265. image,
  266. padding,
  267. mode=PaddingMode.CONSTANT,
  268. constant_values=constant_values,
  269. data_format=data_format,
  270. input_data_format=input_data_format,
  271. )
  272. return padded_image
  273. def pad(
  274. self,
  275. images: List[np.ndarray],
  276. constant_values: Union[float, Iterable[float]] = 0,
  277. return_pixel_mask: bool = True,
  278. return_tensors: Optional[Union[str, TensorType]] = None,
  279. data_format: Optional[ChannelDimension] = None,
  280. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  281. ) -> BatchFeature:
  282. """
  283. For a list of images, for each images, pads a batch of images to the bottom and right of the image with zeros to the size of largest height and width.
  284. For each sample in the batch, pads the sample with empty images to the max_number of images per sample in the batch. Optionally returns a pixel mask.
  285. Args:
  286. images (`np.ndarray`):
  287. List of list of images to pad. Pads to the largest height and width in the batch.
  288. constant_values (`float` or `Iterable[float]`, *optional*):
  289. The value to use for the padding if `mode` is `"constant"`.
  290. return_pixel_mask (`bool`, *optional*, defaults to `True`):
  291. Whether to return a pixel mask.
  292. return_tensors (`str` or `TensorType`, *optional*):
  293. The type of tensors to return. Can be one of:
  294. - Unset: Return a list of `np.ndarray`.
  295. - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
  296. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
  297. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
  298. - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
  299. data_format (`str` or `ChannelDimension`, *optional*):
  300. The channel dimension format of the image. If not provided, it will be the same as the input image.
  301. input_data_format (`ChannelDimension` or `str`, *optional*):
  302. The channel dimension format of the input image. If not provided, it will be inferred.
  303. """
  304. pad_size = get_max_height_width(images, input_data_format=input_data_format)
  305. batch_size = len(images)
  306. max_num_images = max(len(images_) for images_ in images)
  307. input_data_format = (
  308. infer_channel_dimension_format(images[0][0]) if input_data_format is None else input_data_format
  309. )
  310. data_format = input_data_format if data_format is None else data_format
  311. def empty_image(size, input_data_format):
  312. if input_data_format == ChannelDimension.FIRST:
  313. return np.zeros((3, *size), dtype=np.uint8)
  314. elif input_data_format == ChannelDimension.LAST:
  315. return np.zeros((*size, 3), dtype=np.uint8)
  316. raise ValueError("Invalid channel dimension format.")
  317. padded_images_list = [
  318. [empty_image(pad_size, data_format) for _ in range(max_num_images)] for _ in range(batch_size)
  319. ]
  320. padded_masks = [[np.zeros(pad_size) for _ in range(max_num_images)] for _ in range(batch_size)]
  321. for batch_idx in range(batch_size):
  322. for sample_idx, image in enumerate(images[batch_idx]):
  323. padded_images_list[batch_idx][sample_idx] = self._pad_image(
  324. image,
  325. pad_size,
  326. constant_values=constant_values,
  327. data_format=data_format,
  328. input_data_format=input_data_format,
  329. )
  330. padded_masks[batch_idx][sample_idx] = make_pixel_mask(
  331. image, output_size=pad_size, input_data_format=input_data_format
  332. )
  333. padded_masks = padded_masks if return_pixel_mask else None
  334. return padded_images_list, padded_masks
  335. def _crop(
  336. self,
  337. im: np.ndarray,
  338. w1: int,
  339. h1: int,
  340. w2: int,
  341. h2: int,
  342. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  343. ) -> np.ndarray:
  344. if input_data_format == ChannelDimension.FIRST:
  345. return im[:, h1:h2, w1:w2]
  346. elif input_data_format == ChannelDimension.LAST:
  347. return im[h1:h2, w1:w2, :]
  348. def split_image(
  349. self,
  350. image: np.ndarray,
  351. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  352. ):
  353. """
  354. Split an image into 4 equal sub-images, and the concatenate that sequence with the original image.
  355. That means that a single image becomes a sequence of 5 images.
  356. This is a "trick" to spend more compute on each image with no changes in the vision encoder.
  357. Args:
  358. image (`np.ndarray`):
  359. Images to split.
  360. input_data_format (`ChannelDimension` or `str`, *optional*):
  361. The channel dimension format of the input image. If not provided, it will be inferred.
  362. """
  363. height, width = get_image_size(image, input_data_format)
  364. mid_width = width // 2
  365. mid_height = height // 2
  366. return [
  367. self._crop(image, 0, 0, mid_width, mid_height, input_data_format),
  368. self._crop(image, mid_width, 0, width, mid_height, input_data_format),
  369. self._crop(image, 0, mid_height, mid_width, height, input_data_format),
  370. self._crop(image, mid_width, mid_height, width, height, input_data_format),
  371. image,
  372. ]
  373. def preprocess(
  374. self,
  375. images: ImageInput,
  376. do_convert_rgb: Optional[bool] = None,
  377. do_resize: Optional[bool] = None,
  378. size: Optional[Dict[str, int]] = None,
  379. resample: PILImageResampling = None,
  380. do_rescale: Optional[bool] = None,
  381. rescale_factor: Optional[float] = None,
  382. do_normalize: Optional[bool] = None,
  383. image_mean: Optional[Union[float, List[float]]] = None,
  384. image_std: Optional[Union[float, List[float]]] = None,
  385. do_pad: Optional[bool] = None,
  386. do_image_splitting: Optional[bool] = None,
  387. return_tensors: Optional[Union[str, TensorType]] = None,
  388. input_data_format: Optional[ChannelDimension] = None,
  389. data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
  390. ):
  391. """
  392. Preprocess a batch of images.
  393. Args:
  394. images (`ImageInput`):
  395. A list of images to preprocess.
  396. do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
  397. Whether to convert the image to RGB.
  398. do_resize (`bool`, *optional*, defaults to `self.do_resize`):
  399. Whether to resize the image.
  400. size (`Dict[str, int]`, *optional*, defaults to `self.size`):
  401. Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
  402. the longest edge resized to keep the input aspect ratio.
  403. resample (`int`, *optional*, defaults to `self.resample`):
  404. Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
  405. has an effect if `do_resize` is set to `True`.
  406. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
  407. Whether to rescale the image.
  408. rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
  409. Rescale factor to rescale the image by if `do_rescale` is set to `True`.
  410. do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
  411. Whether to normalize the image.
  412. image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
  413. Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
  414. image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
  415. Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
  416. `True`.
  417. do_pad (`bool`, *optional*, defaults to `self.do_pad`):
  418. Whether or not to pad the images to the largest height and width in the batch.
  419. do_image_splitting (`bool`, *optional*, defaults to `self.do_image_splitting`):
  420. Whether to split the image into a sequence 4 equal sub-images concatenated with the original image. That
  421. strategy was first introduced in https://arxiv.org/abs/2311.06607.
  422. return_tensors (`str` or `TensorType`, *optional*):
  423. The type of tensors to return. Can be one of:
  424. - Unset: Return a list of `np.ndarray`.
  425. - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
  426. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
  427. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
  428. - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
  429. data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
  430. The channel dimension format for the output image. Can be one of:
  431. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  432. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  433. - Unset: Use the channel dimension format of the input image.
  434. input_data_format (`ChannelDimension` or `str`, *optional*):
  435. The channel dimension format for the input image. If unset, the channel dimension format is inferred
  436. from the input image. Can be one of:
  437. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  438. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  439. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  440. """
  441. do_resize = do_resize if do_resize is not None else self.do_resize
  442. size = size if size is not None else self.size
  443. resample = resample if resample is not None else self.resample
  444. do_rescale = do_rescale if do_rescale is not None else self.do_rescale
  445. rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
  446. do_normalize = do_normalize if do_normalize is not None else self.do_normalize
  447. image_mean = image_mean if image_mean is not None else self.image_mean
  448. image_std = image_std if image_std is not None else self.image_std
  449. do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
  450. do_pad = do_pad if do_pad is not None else self.do_pad
  451. do_image_splitting = do_image_splitting if do_image_splitting is not None else self.do_image_splitting
  452. images_list = make_list_of_images(images)
  453. if not valid_images(images_list[0]):
  454. raise ValueError(
  455. "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
  456. "torch.Tensor, tf.Tensor or jax.ndarray."
  457. )
  458. validate_preprocess_arguments(
  459. do_rescale=do_rescale,
  460. rescale_factor=rescale_factor,
  461. do_normalize=do_normalize,
  462. image_mean=image_mean,
  463. image_std=image_std,
  464. do_resize=do_resize,
  465. size=size,
  466. resample=resample,
  467. )
  468. if do_convert_rgb:
  469. images_list = [[convert_to_rgb(image) for image in images] for images in images_list]
  470. # All transformations expect numpy arrays.
  471. images_list = [[to_numpy_array(image) for image in images] for images in images_list]
  472. if is_scaled_image(images_list[0][0]) and do_rescale:
  473. logger.warning_once(
  474. "It looks like you are trying to rescale already rescaled images. If the input"
  475. " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
  476. )
  477. if input_data_format is None:
  478. # We assume that all images have the same channel dimension format.
  479. input_data_format = infer_channel_dimension_format(images_list[0][0])
  480. if do_image_splitting:
  481. new_images_list = []
  482. for images in images_list:
  483. new_images = []
  484. for image in images:
  485. new_images.extend(self.split_image(image, input_data_format))
  486. new_images_list.append(new_images)
  487. images_list = new_images_list
  488. if do_resize:
  489. images_list = [
  490. [
  491. self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
  492. for image in images
  493. ]
  494. for images in images_list
  495. ]
  496. if do_rescale:
  497. images_list = [
  498. [
  499. self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
  500. for image in images
  501. ]
  502. for images in images_list
  503. ]
  504. if do_normalize:
  505. images_list = [
  506. [
  507. self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
  508. for image in images
  509. ]
  510. for images in images_list
  511. ]
  512. pixel_attention_mask = None
  513. if do_pad:
  514. images_list, pixel_attention_mask = self.pad(
  515. images_list, return_pixel_mask=True, return_tensors=return_tensors, input_data_format=input_data_format
  516. )
  517. if data_format is not None:
  518. images_list = [
  519. [
  520. to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
  521. for image in images
  522. ]
  523. for images in images_list
  524. ]
  525. data = {"pixel_values": np.array(images_list) if do_pad else images_list} # Faster tensor conversion
  526. if pixel_attention_mask is not None:
  527. data["pixel_attention_mask"] = np.array(pixel_attention_mask) if do_pad else pixel_attention_mask
  528. return BatchFeature(data=data, tensor_type=return_tensors)