image_processing_mllama.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. # coding=utf-8
  2. # Copyright 2024 The HuggingFace Inc. team.
  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. import math
  16. from functools import lru_cache
  17. from typing import Dict, List, Optional, Tuple, Union
  18. import numpy as np
  19. from ...image_processing_utils import BaseImageProcessor, BatchFeature
  20. from ...image_transforms import (
  21. PaddingMode,
  22. get_image_size,
  23. pad,
  24. resize,
  25. )
  26. from ...image_utils import (
  27. IMAGENET_STANDARD_MEAN,
  28. IMAGENET_STANDARD_STD,
  29. ChannelDimension,
  30. ImageInput,
  31. PILImageResampling,
  32. infer_channel_dimension_format,
  33. is_valid_image,
  34. is_vision_available,
  35. to_numpy_array,
  36. validate_preprocess_arguments,
  37. )
  38. from ...utils import TensorType, logging
  39. if is_vision_available():
  40. import PIL
  41. from PIL import Image
  42. logger = logging.get_logger(__name__)
  43. @lru_cache(maxsize=10)
  44. def get_all_supported_aspect_ratios(max_image_tiles: int) -> List[Tuple[int, int]]:
  45. """
  46. Computes all allowed aspect ratios for a given maximum number of input tiles.
  47. This function calculates all possible arrangements of tiles that can be formed
  48. within the constraint of the maximum number of tiles. Each arrangement is
  49. represented by its aspect ratio (width/height) and the corresponding tile configuration.
  50. Args:
  51. max_image_tiles (`int`):
  52. The maximum number of tiles allowed.
  53. Returns:
  54. `List[Tuple[int, int]]`: A list of tuples, each tuple representing a valid (width, height)
  55. configuration in terms of number of tiles.
  56. Example:
  57. >>> get_all_supported_aspect_ratios(4)
  58. [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (3, 1), (4, 1)]
  59. """
  60. aspect_ratios = []
  61. for width in range(1, max_image_tiles + 1):
  62. for height in range(1, max_image_tiles + 1):
  63. if width * height <= max_image_tiles:
  64. aspect_ratios.append((width, height))
  65. return aspect_ratios
  66. def get_image_size_fit_to_canvas(
  67. image_height: int,
  68. image_width: int,
  69. canvas_height: int,
  70. canvas_width: int,
  71. tile_size: int,
  72. ) -> Tuple[int, int]:
  73. """
  74. Calculates the new size of an image to fit within a canvas while maintaining aspect ratio.
  75. This function calculates the optimal size for an image to fit within a canvas defined by
  76. canvas_height and canvas_width, while ensuring that the image dimensions are not smaller than
  77. tile_size. If the image is larger than the canvas, the returned size will fit within the canvas.
  78. If the image already fits within the canvas, the size remains unchanged.
  79. The aspect ratio of the original image is preserved.
  80. Args:
  81. image_height (`int`):
  82. The height of the original image.
  83. image_width (`int`):
  84. The width of the original image.
  85. canvas_height (`int`):
  86. The height of the canvas.
  87. canvas_width (`int`):
  88. The width of the canvas.
  89. tile_size (`int`):
  90. The tile size.
  91. Returns:
  92. `Tuple[int, int]`: A tuple containing the new height and width of the image.
  93. """
  94. # Set target image size in between `tile_size` and canvas_size
  95. target_width = np.clip(image_width, tile_size, canvas_width)
  96. target_height = np.clip(image_height, tile_size, canvas_height)
  97. scale_h = target_height / image_height
  98. scale_w = target_width / image_width
  99. if scale_w < scale_h:
  100. new_width = target_width
  101. new_height = min(math.floor(image_height * scale_w), target_height)
  102. else:
  103. new_height = target_height
  104. new_width = min(math.floor(image_width * scale_h), target_width)
  105. return new_height, new_width
  106. @lru_cache(maxsize=100)
  107. def get_optimal_tiled_canvas(
  108. image_height: int,
  109. image_width: int,
  110. max_image_tiles: int,
  111. tile_size: int,
  112. ) -> Tuple[int, int]:
  113. r"""
  114. Determines the best canvas based on image and tile size and maximum number of tiles.
  115. First, calculates possible resolutions based on the maximum number of tiles and tile size.
  116. For example for max_image_tiles=2, tile_size=100, possible tile arrangements are:
  117. [(1, 1), (1, 2), (2, 1)] and corresponding canvas sizes are:
  118. [(100, 100), (100, 200), (200, 100)]
  119. For each possible resolution, calculates the scaling factors for
  120. width and height, and selects the smallest one, which is the limiting side.
  121. E.g. to match the canvas you can upscale height by 2x, and width by 1.5x,
  122. therefore, the maximum upscaling you can do is min(2, 1.5) = 1.5.
  123. If upscaling is possible (any of the scaling factors is greater than 1),
  124. then picks the smallest upscaling factor > 1.
  125. If upscaling is not possible, then picks the largest scaling factor <= 1, i.e.
  126. reduce downscaling as much as possible.
  127. If there are multiple resolutions with the same max scale, we pick the one with the lowest area,
  128. to minimize padding. E.g., the same image can be upscaled to 224x224 and 224x448, but the latter
  129. has more padding.
  130. Example of canvases made from tiles:
  131. To visualize how the image can fit onto different tile grids, let's try fitting an ASCII cat into the tiles.
  132. Here's an ASCII cat image you want to fit into the tiles:
  133. /\_/\
  134. ( o.o )
  135. > ^ <
  136. If `num_tiles=6`, possible tile grids would look like this:
  137. **2x3 Canvas (2 tiles wide, 3 tiles tall)**: -> total of 6 tiles
  138. +-------+-------+
  139. | /\_/\ | 0 | <- Cat image split across two tiles horizontally
  140. +-------+-------+
  141. | > ^ < | 0 | <- Remaining part of the cat occupies the left tile
  142. +-------+-------+
  143. |( o.o )| 0 |
  144. +-------+-------+
  145. **3x2 Canvas (3 tiles wide, 2 tiles tall)**: -> total of 6 tiles
  146. +-------+-------+-------+
  147. | /\_/\ |( o.o )| 0 | <- Cat image occupies the first two tiles, 1 tile remains empty
  148. +-------+-------+-------+
  149. | > ^ < | 0 | 0 | <- Remaining part of the cat occupies the left tile
  150. +-------+-------+-------+
  151. **1x6 Canvas (1 tile wide, 6 tiles tall)**: -> total of 6 tiles
  152. +-------+
  153. | /\_/\ | <- Top part of the cat
  154. +-------+
  155. |( o.o )| <- Middle part of the cat
  156. +-------+
  157. | > ^ < | <- Bottom part of the cat
  158. +-------+
  159. | 0 |
  160. +-------+
  161. | 0 |
  162. +-------+
  163. | 0 |
  164. +-------+
  165. Given that the tiles you get depend on the chosen aspect ratio, you have to add
  166. embedding in the modeling code to help it know if it got a 3x2 or a 1x6 or a 2x3
  167. aspect ratio.
  168. The function tests these arrangements to find the smallest canvas where the image fits.
  169. If multiple canvases fit, it selects the one where the dimensions are closest to the image size.
  170. In this case the first canvas is the closest to the original image.
  171. You then feed all of the tiles to the model:
  172. +-------+-------+-------+-------+-------+-------+
  173. - | /\_/\ |( o.o )| > ^ < | 0 | 0 | 0 | <- Last canvas
  174. +-------+-------+-------+-------+-------+-------+
  175. +-------+-------+-------+-------+-------+-------+
  176. - | /\_/\ | 0 |( o.o )| 0 | > ^ < | 0 | <- First canvas
  177. +-------+-------+-------+-------+-------+-------+
  178. +-------+-------+-------+-------+-------+-------+
  179. - | /\_/\ |( o.o )| 0 | > ^ < | 0 | 0 | <- second canvas
  180. +-------+-------+-------+-------+-------+-------+
  181. For each tile, you have num_channels (usually RGB so 3), tile_width, tile_height
  182. Args:
  183. image_height (`int`):
  184. The height of the image.
  185. image_width (`int`):
  186. The width of the image.
  187. max_image_tiles (`int`):
  188. The maximum number of tiles any image can be split into.
  189. tile_size (`int`):
  190. The tile size.
  191. Returns:
  192. `Tuple[int, int]`: The best canvas resolution [height, width] for the given image.
  193. """
  194. possible_tile_arrangements = get_all_supported_aspect_ratios(max_image_tiles)
  195. possible_canvas_sizes = np.array(possible_tile_arrangements) * tile_size
  196. # get all possible resolutions heights/widths
  197. target_heights, target_widths = np.array(possible_canvas_sizes).T
  198. # get scaling factors to resize the image without distortion
  199. scale_h = target_heights / image_height
  200. scale_w = target_widths / image_width
  201. # get the min scale between width and height (limiting side -> no distortion)
  202. scales = np.where(scale_w > scale_h, scale_h, scale_w)
  203. # filter only scales that allow upscaling
  204. upscaling_options = scales[scales >= 1]
  205. if len(upscaling_options) > 0:
  206. selected_scale = np.min(upscaling_options)
  207. else:
  208. # no upscaling possible,
  209. # get the minimum downscaling (max scale for scales<1)
  210. downscaling_options = scales[scales < 1]
  211. selected_scale = np.max(downscaling_options)
  212. # get all resolutions that support this scaling factor,
  213. # e.g. you can upscale to 224x224, 224x448, 224x672 without distortion
  214. chosen_canvas = possible_canvas_sizes[scales == selected_scale]
  215. # if there are multiple resolutions,
  216. # get the one with minimum area to reduce padding
  217. if len(chosen_canvas) > 1:
  218. areas = chosen_canvas[:, 0] * chosen_canvas[:, 1]
  219. optimal_idx = np.argmin(areas)
  220. optimal_canvas = chosen_canvas[optimal_idx]
  221. else:
  222. optimal_canvas = chosen_canvas[0]
  223. return optimal_canvas
  224. def split_to_tiles(image: np.ndarray, num_tiles_height: int, num_tiles_width: int) -> np.ndarray:
  225. """
  226. Split an image into a specified number of tiles along its width and height dimensions.
  227. Args:
  228. image (`np.ndarray`):
  229. Input image with shape (num_channels, height, width).
  230. num_tiles_height (`int`):
  231. Number of tiles to split the image into along its height.
  232. num_tiles_width (`int`):
  233. Number of tiles to split the image into along its width.
  234. Returns:
  235. `np.ndarray`:
  236. Array of image tiles with shape (num_tiles_width * num_tiles_height, num_channels, tile_height, tile_width).
  237. """
  238. num_channels, height, width = image.shape
  239. tile_height = height // num_tiles_height
  240. tile_width = width // num_tiles_width
  241. image = image.reshape(num_channels, num_tiles_height, tile_height, num_tiles_width, tile_width)
  242. # Permute to (num_tiles_height, num_tiles_width, num_channels, tile_height, tile_width)
  243. image = image.transpose(1, 3, 0, 2, 4)
  244. # Reshape into the desired output shape (num_tiles_width * num_tiles_height, num_channels, tile_height, tile_width)
  245. image = image.reshape(num_tiles_width * num_tiles_height, num_channels, tile_height, tile_width)
  246. return np.ascontiguousarray(image)
  247. def build_aspect_ratio_mask(aspect_ratios: List[List[Tuple[int, int]]], max_image_tiles: int) -> np.ndarray:
  248. """
  249. Builds a mask for the aspect ratios of the images.
  250. Args:
  251. aspect_ratios (`List[List[Tuple[int, int]]]`):
  252. A list of lists containing aspect ratios for each image in the batch.
  253. Each aspect ratio is represented as a tuple of (width, height) in terms of number of tiles.
  254. max_image_tiles (`int`):
  255. The maximum number of tiles any image can be split into.
  256. Returns:
  257. `np.ndarray`: A 3D numpy array of shape (batch_size, max_num_images, max_image_tiles).
  258. The mask contains 1s for valid tiles and 0s for padding.
  259. """
  260. batch_size = len(aspect_ratios)
  261. max_num_images = max([len(row) for row in aspect_ratios])
  262. aspect_ratio_mask = np.zeros((batch_size, max_num_images, max_image_tiles), dtype=np.int64)
  263. # Set the first tile to 1 for all aspect ratios
  264. # because in original implementation aspect ratios are padded with (1, 1),
  265. # but original code examples are not built to handle batches, so we might remove it later
  266. aspect_ratio_mask[:, :, 0] = 1
  267. # Set the aspect ratio mask for the rest of the tiles
  268. for i, sample_aspect_ratios in enumerate(aspect_ratios):
  269. for j, (num_tiles_w, num_tiles_h) in enumerate(sample_aspect_ratios):
  270. aspect_ratio_mask[i, j, : num_tiles_w * num_tiles_h] = 1
  271. return aspect_ratio_mask
  272. def pack_images(
  273. batch_images: List[List[np.ndarray]],
  274. max_image_tiles: int,
  275. ) -> Tuple[np.ndarray, List[List[int]]]:
  276. """
  277. Stack a list of lists of images with variable lengths into a numpy array, applying zero padding as needed.
  278. Each list in the input represents a batch sample, and each image within a list is expected to be
  279. pre-split into tiles. The resulting array will have a shape of
  280. (batch_size, max_num_images, max_image_tiles, channels, tile_height, tile_width).
  281. Args:
  282. batch_images (`List[List[np.ndarray]]`):
  283. A list of lists of image tiles. Each inner list represents
  284. a batch sample containing multiple images, where each image is pre-split into tiles.
  285. The shape of each tile array is (num_tiles, channels, tile_height, tile_width).
  286. max_image_tiles (int):
  287. The maximum number of tiles any image was potantially split.
  288. Returns:
  289. `Tuple[np.ndarray, List[List[int]]]`: A tuple containing:
  290. - stacked_images (`np.ndarray`):
  291. A numpy array of stacked images with shape
  292. (batch_size, max_num_images, max_image_tiles, channels, tile_height, tile_width).
  293. - all_num_tiles (`List[List[int]]`):
  294. A list of lists containing the number of tiles
  295. for each image in each batch sample.
  296. """
  297. # Determine output shape
  298. batch_size = len(batch_images)
  299. max_num_images = max([len(images) for images in batch_images])
  300. shapes = [image.shape for images in batch_images for image in images]
  301. _, channels, tile_height, tile_width = shapes[0]
  302. # Initialize the stacked images array with zeros
  303. stacked_images = np.zeros(
  304. (batch_size, max_num_images, max_image_tiles, channels, tile_height, tile_width),
  305. dtype=np.float32,
  306. )
  307. # Fill the stacked images array with the tiled images from the batch
  308. all_num_tiles = []
  309. for i, images in enumerate(batch_images):
  310. num_sample_tiles = []
  311. for j, image in enumerate(images):
  312. num_tiles = image.shape[0]
  313. stacked_images[i, j, :num_tiles] = image
  314. num_sample_tiles.append(num_tiles)
  315. all_num_tiles.append(num_sample_tiles)
  316. return stacked_images, all_num_tiles
  317. def pack_aspect_ratios(aspect_ratios: List[List[Tuple[int, int]]], pad_value: int = 1) -> np.ndarray:
  318. """
  319. Stack a list of aspect ratios into a numpy array.
  320. Args:
  321. aspect_ratios (`List[List[Tuple[int, int]]]`):
  322. A list of aspect ratios.
  323. pad_value (`int`, *optional*, defaults to 1):
  324. The value to pad the aspect ratios with.
  325. Returns:
  326. `np.ndarray`:
  327. The aspect ratios stacked into a numpy array with shape (batch_size, max_num_images, 2).
  328. """
  329. batch_size = len(aspect_ratios)
  330. max_num_images = max([len(row) for row in aspect_ratios])
  331. aspect_ratios_stacked = np.full((batch_size, max_num_images, 2), pad_value, dtype=np.int64)
  332. for i, row in enumerate(aspect_ratios):
  333. if len(row) > 0:
  334. aspect_ratios_stacked[i, : len(row)] = np.array(row)
  335. return aspect_ratios_stacked
  336. def convert_aspect_ratios_to_ids(aspect_ratios: List[List[Tuple[int, int]]], max_image_tiles: int) -> np.ndarray:
  337. """
  338. Convert aspect ratio tuples to unique ids.
  339. For batch padding we use 0, because there might be different number of images in each batch.
  340. The aspect ratio ids start from 1, with 1 corresponding to the first supported aspect ratio.
  341. Args:
  342. aspect_ratios (`List[List[Tuple[int, int]]]`):
  343. A list of aspect ratios for each image in the batch.
  344. max_image_tiles (`int`):
  345. The maximum number of tiles any image can be split into.
  346. Returns:
  347. `np.ndarray`:
  348. The aspect ratios ids as a numpy array with shape (batch_size, max_num_images).
  349. Each id corresponds to the index of the aspect ratio in the list of supported aspect ratios,
  350. offset by 1 (so 0 can be used for padding).
  351. """
  352. batch_size = len(aspect_ratios)
  353. max_num_images = max([len(row) for row in aspect_ratios])
  354. supported_aspect_ratios = get_all_supported_aspect_ratios(max_image_tiles)
  355. aspect_ratios_ids = np.zeros((batch_size, max_num_images), dtype=np.int64)
  356. for i, sample_aspect_ratios in enumerate(aspect_ratios):
  357. for j, (num_tiles_h, num_tiles_w) in enumerate(sample_aspect_ratios):
  358. aspect_ratios_ids[i, j] = supported_aspect_ratios.index((num_tiles_h, num_tiles_w)) + 1
  359. return aspect_ratios_ids
  360. def to_channel_dimension_format(
  361. image: np.ndarray,
  362. channel_dim: Union[ChannelDimension, str],
  363. input_channel_dim: Optional[Union[ChannelDimension, str]] = None,
  364. ) -> np.ndarray:
  365. """
  366. Converts `image` to the channel dimension format specified by `channel_dim`.
  367. Args:
  368. image (`numpy.ndarray`):
  369. The image to have its channel dimension set.
  370. channel_dim (`ChannelDimension`):
  371. The channel dimension format to use.
  372. input_channel_dim (`ChannelDimension`, *optional*):
  373. The channel dimension format of the input image. If not provided, it will be inferred from the input image.
  374. Returns:
  375. `np.ndarray`:
  376. The image with the channel dimension set to `channel_dim`.
  377. """
  378. if not isinstance(image, np.ndarray):
  379. raise ValueError(f"Input image must be of type np.ndarray, got {type(image)}")
  380. if input_channel_dim is None:
  381. input_channel_dim = infer_channel_dimension_format(image)
  382. target_channel_dim = ChannelDimension(channel_dim)
  383. if input_channel_dim == target_channel_dim:
  384. return image
  385. if target_channel_dim == ChannelDimension.FIRST:
  386. image = image.transpose((2, 0, 1))
  387. elif target_channel_dim == ChannelDimension.LAST:
  388. image = image.transpose((1, 2, 0))
  389. else:
  390. raise ValueError("Unsupported channel dimension format: {}".format(channel_dim))
  391. return image
  392. # Copied from transformers.models.idefics2.image_processing_idefics2.convert_to_rgb
  393. def convert_to_rgb(image: ImageInput) -> ImageInput:
  394. """
  395. Converts an image to RGB format. Only converts if the image is of type PIL.Image.Image, otherwise returns the image
  396. as is.
  397. Args:
  398. image (Image):
  399. The image to convert.
  400. """
  401. if not isinstance(image, PIL.Image.Image):
  402. return image
  403. # `image.convert("RGB")` would only work for .jpg images, as it creates a wrong background
  404. # for transparent images. The call to `alpha_composite` handles this case
  405. if image.mode == "RGB":
  406. return image
  407. image_rgba = image.convert("RGBA")
  408. background = Image.new("RGBA", image_rgba.size, (255, 255, 255))
  409. alpha_composite = Image.alpha_composite(background, image_rgba)
  410. alpha_composite = alpha_composite.convert("RGB")
  411. return alpha_composite
  412. # Modified from transformers.models.idefics2.image_processing_idefics2.make_list_of_images
  413. def make_list_of_images(images: ImageInput) -> List[List[Optional[np.ndarray]]]:
  414. """
  415. Convert a single image or a list of images to a list of numpy arrays.
  416. Args:
  417. images (`ImageInput`):
  418. A single image or a list of images.
  419. Returns:
  420. A list of numpy arrays.
  421. """
  422. # If it's a single image, convert it to a list of lists
  423. if is_valid_image(images):
  424. output_images = [[images]]
  425. # If it's a list of images, it's a single batch, so convert it to a list of lists
  426. elif isinstance(images, (list, tuple)) and is_valid_list_of_images(images):
  427. output_images = [images]
  428. # If it's a list of batches, it's already in the right format
  429. elif (
  430. isinstance(images, (list, tuple))
  431. and all(isinstance(images_i, (list, tuple)) for images_i in images)
  432. and any(is_valid_list_of_images(images_i) for images_i in images)
  433. ):
  434. output_images = images
  435. else:
  436. raise ValueError(
  437. "Invalid input type. Must be a single image, a list of images, or a list of batches of images."
  438. )
  439. return output_images
  440. def is_valid_list_of_images(images: List):
  441. return images and all(is_valid_image(image) for image in images)
  442. def _validate_size(size: Dict[str, int]) -> None:
  443. if not ("height" in size and "width" in size):
  444. raise ValueError(f"Argument `size` must be a dictionary with keys 'height' and 'width'. Got: {size}")
  445. if size["height"] != size["width"]:
  446. raise ValueError(f"Argument `size` must have the same height and width, got {size}")
  447. def _validate_mllama_preprocess_arguments(do_resize, size, do_pad, max_image_tiles):
  448. if not do_pad:
  449. raise ValueError("MllamaImageProcessor doesn't support `do_pad=False` mode.")
  450. if not do_resize:
  451. raise ValueError("MllamaImageProcessor doesn't support `do_resize=False` mode.")
  452. if max_image_tiles is None or max_image_tiles <= 0:
  453. raise ValueError(f"MllamaImageProcessor `max_image_tiles` must be a positive integer, got {max_image_tiles}.")
  454. _validate_size(size)
  455. class MllamaImageProcessor(BaseImageProcessor):
  456. """
  457. Constructs a Mllama image processor.
  458. Args:
  459. do_convert_rgb (`bool`, *optional*, defaults to `True`):
  460. Whether to convert the image to RGB. This is useful if the input image is of a different format e.g. RGBA.
  461. Only has an effect if the input image is in the PIL format.
  462. do_resize (`bool`, *optional*, defaults to `True`):
  463. Whether to resize the image.
  464. size (`Dict[str, int]`, *optional*, defaults to `self.size`):
  465. Size of the image tile. Should be a dictionary containing 'height' and 'width' keys, both with integer values.
  466. The height and width values should be equal.
  467. resample (`int`, *optional*, defaults to `Resampling.BILINEAR`):
  468. Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
  469. has an effect if `do_resize` is set to `True`.
  470. do_rescale (`bool`, *optional*, defaults to `True`):
  471. Whether to rescale the image.
  472. rescale_factor (`float`, *optional*, defaults to 0.0):
  473. Rescale factor to rescale the image by if `do_rescale` is set to `True`.
  474. do_normalize (`bool`, *optional*, defaults to `True`):
  475. Whether to normalize the image.
  476. image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
  477. Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
  478. image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
  479. Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
  480. `True`.
  481. do_pad (`bool`, *optional*, defaults to `True`):
  482. Whether or not to pad the images to the largest height and width in the batch.
  483. max_image_tiles (`int`, *optional*, defaults to 4):
  484. The maximum number of tiles to split the image into.
  485. """
  486. model_input_names = ["pixel_values", "num_tiles", "aspect_ratio_ids", "aspect_ratio_mask"]
  487. def __init__(
  488. self,
  489. do_convert_rgb: bool = True,
  490. do_resize: bool = True,
  491. size: Optional[Dict[str, int]] = None,
  492. resample: PILImageResampling = PILImageResampling.BILINEAR,
  493. do_rescale: bool = True,
  494. rescale_factor: float = 1 / 255,
  495. do_normalize: bool = True,
  496. image_mean: Optional[Union[float, List[float]]] = None,
  497. image_std: Optional[Union[float, List[float]]] = None,
  498. do_pad: bool = True,
  499. max_image_tiles: int = 4,
  500. **kwargs,
  501. ) -> None:
  502. super().__init__(**kwargs)
  503. self.do_convert_rgb = do_convert_rgb
  504. self.do_resize = do_resize
  505. self.size = size if size is not None else {"height": 224, "width": 224}
  506. self.resample = resample
  507. self.do_rescale = do_rescale
  508. self.rescale_factor = rescale_factor
  509. self.do_normalize = do_normalize
  510. self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
  511. self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
  512. self.do_pad = do_pad
  513. self.max_image_tiles = max_image_tiles
  514. _validate_mllama_preprocess_arguments(self.do_resize, self.size, self.do_pad, self.max_image_tiles)
  515. def preprocess(
  516. self,
  517. images: ImageInput,
  518. do_convert_rgb: Optional[bool] = None,
  519. do_resize: Optional[bool] = None,
  520. size: Optional[Dict[str, int]] = None,
  521. resample: Optional[PILImageResampling] = None,
  522. do_rescale: Optional[bool] = None,
  523. rescale_factor: Optional[float] = None,
  524. do_normalize: Optional[bool] = None,
  525. image_mean: Optional[Union[float, List[float]]] = None,
  526. image_std: Optional[Union[float, List[float]]] = None,
  527. do_pad: Optional[bool] = None,
  528. max_image_tiles: Optional[int] = None,
  529. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  530. return_tensors: Optional[Union[str, TensorType]] = None,
  531. ):
  532. """
  533. Preprocess a batch of images.
  534. Args:
  535. images (`ImageInput`):
  536. A list of images to preprocess.
  537. do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
  538. Whether to convert the image to RGB.
  539. do_resize (`bool`, *optional*, defaults to `self.do_resize`):
  540. Whether to resize the image.
  541. size (`Dict[str, int]`, *optional*, defaults to `self.size`):
  542. Size of the image tile. Should be a dictionary containing 'height' and 'width' keys, both with integer values.
  543. The height and width values should be equal.
  544. resample (`int`, *optional*, defaults to `self.resample`):
  545. Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
  546. has an effect if `do_resize` is set to `True`.
  547. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
  548. Whether to rescale the image.
  549. rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
  550. Rescale factor to rescale the image by if `do_rescale` is set to `True`.
  551. do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
  552. Whether to normalize the image.
  553. image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
  554. Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
  555. image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
  556. Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
  557. `True`.
  558. do_pad (`bool`, *optional*, defaults to `self.do_pad`):
  559. Whether or not to pad the images to the largest height and width in the batch.
  560. max_image_tiles (`int`, *optional*, defaults to `self.max_image_tiles`):
  561. The maximum number of tiles to split the image into.
  562. input_data_format (`ChannelDimension` or `str`, *optional*):
  563. The channel dimension format for the input image. If unset, the channel dimension format is inferred
  564. from the input image. Can be one of:
  565. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  566. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  567. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  568. return_tensors (`str` or `TensorType`, *optional*):
  569. The type of tensors to return. Can be one of:
  570. - Unset: Return a list of `np.ndarray`.
  571. - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
  572. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
  573. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
  574. - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
  575. Returns:
  576. `BatchFeature` of the following structure:
  577. - **pixel_values** (`TensorType`): The preprocessed pixel values.
  578. - **aspect_ratio_ids** (`TensorType`): The aspect ratio ids of the images.
  579. - **num_tiles** (`List[List[int]]`): The number of tiles for each image in the batch.
  580. """
  581. do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
  582. do_resize = do_resize if do_resize is not None else self.do_resize
  583. size = size if size is not None else self.size
  584. resample = resample if resample is not None else self.resample
  585. do_rescale = do_rescale if do_rescale is not None else self.do_rescale
  586. rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
  587. do_normalize = do_normalize if do_normalize is not None else self.do_normalize
  588. image_mean = image_mean if image_mean is not None else self.image_mean
  589. image_std = image_std if image_std is not None else self.image_std
  590. do_pad = do_pad if do_pad is not None else self.do_pad
  591. max_image_tiles = max_image_tiles if max_image_tiles is not None else self.max_image_tiles
  592. validate_preprocess_arguments(
  593. do_rescale=do_rescale,
  594. rescale_factor=rescale_factor,
  595. do_normalize=do_normalize,
  596. image_mean=image_mean,
  597. image_std=image_std,
  598. do_resize=do_resize,
  599. size=size,
  600. resample=resample,
  601. )
  602. # extra validation
  603. _validate_mllama_preprocess_arguments(do_resize, size, do_pad, max_image_tiles)
  604. images_list = make_list_of_images(images)
  605. if self.do_convert_rgb:
  606. images_list = [[convert_to_rgb(image) for image in images] for images in images_list]
  607. images_list = [[to_numpy_array(image) for image in images] for images in images_list]
  608. batch_images = []
  609. batch_aspect_ratios = []
  610. # iterate over batch samples
  611. for images in images_list:
  612. sample_images = []
  613. sample_aspect_ratios = []
  614. # iterate over images in a batch sample
  615. for image in images:
  616. # convert images to channels first format for faster processing
  617. # LAST is slower for `pad` and not supported by `split_to_tiles`
  618. data_format = ChannelDimension.FIRST
  619. image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
  620. # do_resize=False is not supported, validated
  621. image, aspect_ratio = self.resize(
  622. image=image,
  623. size=size,
  624. resample=resample,
  625. max_image_tiles=max_image_tiles,
  626. input_data_format=data_format,
  627. data_format=data_format,
  628. )
  629. # do_pad=False is not supported, validated
  630. image = self.pad(
  631. image=image,
  632. size=size,
  633. aspect_ratio=aspect_ratio,
  634. input_data_format=data_format,
  635. data_format=data_format,
  636. )
  637. if do_rescale:
  638. image = self.rescale(
  639. image=image,
  640. scale=rescale_factor,
  641. input_data_format=input_data_format,
  642. data_format=data_format,
  643. )
  644. if do_normalize:
  645. image = self.normalize(
  646. image=image,
  647. mean=image_mean,
  648. std=image_std,
  649. input_data_format=input_data_format,
  650. data_format=data_format,
  651. )
  652. num_tiles_height, num_tiles_width = aspect_ratio
  653. image = split_to_tiles(image, num_tiles_height, num_tiles_width)
  654. sample_images.append(image)
  655. sample_aspect_ratios.append((num_tiles_height, num_tiles_width))
  656. batch_images.append(sample_images)
  657. batch_aspect_ratios.append(sample_aspect_ratios)
  658. images, num_tiles = pack_images(batch_images, max_image_tiles)
  659. aspect_ratio_ids = convert_aspect_ratios_to_ids(batch_aspect_ratios, max_image_tiles=max_image_tiles)
  660. aspect_ratio_mask = build_aspect_ratio_mask(batch_aspect_ratios, max_image_tiles=max_image_tiles)
  661. # images (np.ndarray) with shape (batch_size, max_num_images, max_image_tiles, channels, tile_height, tile_width)
  662. # aspect_ratio_ids (np.ndarray) with shape (batch_size, max_num_images) - aspect ratio ids for each image, padded to max_num_images with 0
  663. # num_tiles (List[List[int]]) with (batch_size, num_images_in_batch) - real number of tiles for each image, not padded
  664. # aspect_ratio_mask (np.ndarray) with shape (batch_size, max_num_images, max_image_tiles) - number of tiles for each image, padded to max_num_images with 0
  665. encoded_inputs = BatchFeature(
  666. data={
  667. "pixel_values": images,
  668. "aspect_ratio_ids": aspect_ratio_ids,
  669. "aspect_ratio_mask": aspect_ratio_mask,
  670. },
  671. tensor_type=return_tensors,
  672. )
  673. encoded_inputs["num_tiles"] = num_tiles
  674. return encoded_inputs
  675. def pad(
  676. self,
  677. image: np.ndarray,
  678. size: Dict[str, int],
  679. aspect_ratio: Tuple[int, int],
  680. data_format: Optional[Union[str, ChannelDimension]] = None,
  681. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  682. ) -> np.ndarray:
  683. """
  684. Pad an image to the `size` x `aspect_ratio`. For example, if size is {height: 224, width: 224} and aspect ratio is
  685. (1, 2), the image will be padded to 224x448.
  686. Args:
  687. image (`np.ndarray`):
  688. Image to resize.
  689. size (`Dict[str, int]`):
  690. Size of the output image.
  691. aspect_ratio (`Tuple[int, int]`):
  692. The aspect ratio of the image.
  693. data_format (`str` or `ChannelDimension`, *optional*):
  694. The channel dimension format of the image. If not provided, it will be the same as the input image.
  695. input_data_format (`ChannelDimension` or `str`, *optional*):
  696. The channel dimension format of the input image. If not provided, it will be inferred.
  697. Returns:
  698. `np.ndarray`: The padded image.
  699. """
  700. _validate_size(size)
  701. image_height, image_width = get_image_size(image, channel_dim=input_data_format)
  702. num_tiles_height, num_tiles_width = aspect_ratio
  703. padded_height = num_tiles_height * size["height"]
  704. padded_width = num_tiles_width * size["width"]
  705. pad_size = ((0, padded_height - image_height), (0, padded_width - image_width))
  706. image = pad(
  707. image,
  708. pad_size,
  709. mode=PaddingMode.CONSTANT,
  710. constant_values=0,
  711. data_format=data_format,
  712. input_data_format=input_data_format,
  713. )
  714. return image
  715. def resize(
  716. self,
  717. image: np.ndarray,
  718. size: Dict[str, int],
  719. max_image_tiles: int,
  720. resample: PILImageResampling = PILImageResampling.BILINEAR,
  721. data_format: Optional[Union[str, ChannelDimension]] = None,
  722. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  723. ) -> Union[np.ndarray, Tuple[int, int]]:
  724. """
  725. Resizes an image to fit within a tiled canvas while maintaining its aspect ratio.
  726. The optimal canvas size is calculated based on the maximum number of tiles and the tile size.
  727. The function first determines the best tile arrangement for the image, then resizes the image
  728. to fit within this canvas. The resized image and the number of tiles along the height and width
  729. dimensions are returned.
  730. Args:
  731. image (`np.ndarray`):
  732. Image to resize.
  733. size (`Dict[str, int]`):
  734. Size of the output image.
  735. max_image_tiles (`int`):
  736. The maximum number of tiles to split the image into.
  737. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
  738. Resampling filter to use when resizing the image.
  739. data_format (`str` or `ChannelDimension`, *optional*):
  740. The channel dimension format of the image. If not provided, it will be the same as the input image.
  741. input_data_format (`ChannelDimension` or `str`, *optional*):
  742. The channel dimension format of the input image. If not provided, it will be inferred.
  743. Returns:
  744. `Union[np.ndarray, Tuple[int, int]]`: The resized image and a tuple containing the number of tiles
  745. along the height and width dimensions.
  746. """
  747. _validate_size(size)
  748. image_height, image_width = get_image_size(image, channel_dim=input_data_format)
  749. tile_size = size["height"]
  750. canvas_height, canvas_width = get_optimal_tiled_canvas(
  751. image_height=image_height,
  752. image_width=image_width,
  753. max_image_tiles=max_image_tiles,
  754. tile_size=tile_size,
  755. )
  756. num_tiles_height = canvas_height // tile_size
  757. num_tiles_width = canvas_width // tile_size
  758. new_height, new_width = get_image_size_fit_to_canvas(
  759. image_height=image_height,
  760. image_width=image_width,
  761. canvas_height=canvas_height,
  762. canvas_width=canvas_width,
  763. tile_size=tile_size,
  764. )
  765. image = resize(
  766. image,
  767. (new_height, new_width),
  768. resample=resample,
  769. data_format=data_format,
  770. input_data_format=input_data_format,
  771. )
  772. return image, (num_tiles_height, num_tiles_width)