image_transforms.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. # Copyright 2022 The HuggingFace Inc. team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from collections import defaultdict
  15. from collections.abc import Collection, Iterable
  16. from math import ceil
  17. from typing import Optional, Union
  18. import numpy as np
  19. from .image_utils import (
  20. ChannelDimension,
  21. ImageInput,
  22. get_channel_dimension_axis,
  23. get_image_size,
  24. infer_channel_dimension_format,
  25. )
  26. from .utils import ExplicitEnum, TensorType, is_torch_tensor
  27. from .utils.import_utils import (
  28. is_torch_available,
  29. is_vision_available,
  30. requires_backends,
  31. )
  32. if is_vision_available():
  33. import PIL
  34. from .image_utils import PILImageResampling
  35. if is_torch_available():
  36. import torch
  37. def to_channel_dimension_format(
  38. image: np.ndarray,
  39. channel_dim: ChannelDimension | str,
  40. input_channel_dim: ChannelDimension | str | None = None,
  41. ) -> np.ndarray:
  42. """
  43. Converts `image` to the channel dimension format specified by `channel_dim`. The input
  44. can have arbitrary number of leading dimensions. Only last three dimension will be permuted
  45. to format the `image`.
  46. Args:
  47. image (`numpy.ndarray`):
  48. The image to have its channel dimension set.
  49. channel_dim (`ChannelDimension`):
  50. The channel dimension format to use.
  51. input_channel_dim (`ChannelDimension`, *optional*):
  52. The channel dimension format of the input image. If not provided, it will be inferred from the input image.
  53. Returns:
  54. `np.ndarray`: The image with the channel dimension set to `channel_dim`.
  55. """
  56. if not isinstance(image, np.ndarray):
  57. raise TypeError(f"Input image must be of type np.ndarray, got {type(image)}")
  58. if input_channel_dim is None:
  59. input_channel_dim = infer_channel_dimension_format(image)
  60. target_channel_dim = ChannelDimension(channel_dim)
  61. if input_channel_dim == target_channel_dim:
  62. return image
  63. if target_channel_dim == ChannelDimension.FIRST:
  64. axes = list(range(image.ndim - 3)) + [image.ndim - 1, image.ndim - 3, image.ndim - 2]
  65. image = image.transpose(axes)
  66. elif target_channel_dim == ChannelDimension.LAST:
  67. axes = list(range(image.ndim - 3)) + [image.ndim - 2, image.ndim - 1, image.ndim - 3]
  68. image = image.transpose(axes)
  69. else:
  70. raise ValueError(f"Unsupported channel dimension format: {channel_dim}")
  71. return image
  72. def rescale(
  73. image: np.ndarray,
  74. scale: float,
  75. data_format: ChannelDimension | None = None,
  76. dtype: np.dtype = np.float32,
  77. input_data_format: str | ChannelDimension | None = None,
  78. ) -> np.ndarray:
  79. """
  80. Rescales `image` by `scale`.
  81. Args:
  82. image (`np.ndarray`):
  83. The image to rescale.
  84. scale (`float`):
  85. The scale to use for rescaling the image.
  86. data_format (`ChannelDimension`, *optional*):
  87. The channel dimension format of the image. If not provided, it will be the same as the input image.
  88. dtype (`np.dtype`, *optional*, defaults to `np.float32`):
  89. The dtype of the output image. Defaults to `np.float32`. Used for backwards compatibility with feature
  90. extractors.
  91. input_data_format (`ChannelDimension`, *optional*):
  92. The channel dimension format of the input image. If not provided, it will be inferred from the input image.
  93. Returns:
  94. `np.ndarray`: The rescaled image.
  95. """
  96. if not isinstance(image, np.ndarray):
  97. raise TypeError(f"Input image must be of type np.ndarray, got {type(image)}")
  98. rescaled_image = image.astype(np.float64) * scale # Numpy type promotion has changed, so always upcast first
  99. if data_format is not None:
  100. rescaled_image = to_channel_dimension_format(rescaled_image, data_format, input_data_format)
  101. rescaled_image = rescaled_image.astype(dtype) # Finally downcast to the desired dtype at the end
  102. return rescaled_image
  103. def _rescale_for_pil_conversion(image):
  104. """
  105. Detects whether or not the image needs to be rescaled before being converted to a PIL image.
  106. The assumption is that if the image is of type `np.float` and all values are between 0 and 1, it needs to be
  107. rescaled.
  108. """
  109. if image.dtype == np.uint8:
  110. do_rescale = False
  111. elif np.allclose(image, image.astype(int)):
  112. if np.all(image >= 0) and np.all(image <= 255):
  113. do_rescale = False
  114. else:
  115. raise ValueError(
  116. "The image to be converted to a PIL image contains values outside the range [0, 255], "
  117. f"got [{image.min()}, {image.max()}] which cannot be converted to uint8."
  118. )
  119. elif np.all(image >= 0) and np.all(image <= 1):
  120. do_rescale = True
  121. else:
  122. raise ValueError(
  123. "The image to be converted to a PIL image contains values outside the range [0, 1], "
  124. f"got [{image.min()}, {image.max()}] which cannot be converted to uint8."
  125. )
  126. return do_rescale
  127. def to_pil_image(
  128. image: Union[np.ndarray, "PIL.Image.Image", "torch.Tensor"],
  129. do_rescale: bool | None = None,
  130. image_mode: str | None = None,
  131. input_data_format: str | ChannelDimension | None = None,
  132. ) -> "PIL.Image.Image":
  133. """
  134. Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if
  135. needed.
  136. Args:
  137. image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor`):
  138. The image to convert to the `PIL.Image` format.
  139. do_rescale (`bool`, *optional*):
  140. Whether or not to apply the scaling factor (to make pixel values integers between 0 and 255). Will default
  141. to `True` if the image type is a floating type and casting to `int` would result in a loss of precision,
  142. and `False` otherwise.
  143. image_mode (`str`, *optional*):
  144. The mode to use for the PIL image. If unset, will use the default mode for the input image type.
  145. input_data_format (`ChannelDimension`, *optional*):
  146. The channel dimension format of the input image. If unset, will use the inferred format from the input.
  147. Returns:
  148. `PIL.Image.Image`: The converted image.
  149. """
  150. requires_backends(to_pil_image, ["vision"])
  151. if isinstance(image, PIL.Image.Image):
  152. return image
  153. # Convert all tensors to numpy arrays before converting to PIL image
  154. if is_torch_tensor(image):
  155. image = image.numpy()
  156. elif not isinstance(image, np.ndarray):
  157. raise ValueError(f"Input image type not supported: {type(image)}")
  158. # If the channel has been moved to first dim, we put it back at the end.
  159. image = to_channel_dimension_format(image, ChannelDimension.LAST, input_data_format)
  160. # If there is a single channel, we squeeze it, as otherwise PIL can't handle it.
  161. image = np.squeeze(image, axis=-1) if image.shape[-1] == 1 else image
  162. # PIL.Image can only store uint8 values so we rescale the image to be between 0 and 255 if needed.
  163. do_rescale = _rescale_for_pil_conversion(image) if do_rescale is None else do_rescale
  164. if do_rescale:
  165. image = rescale(image, 255)
  166. image = image.astype(np.uint8)
  167. return PIL.Image.fromarray(image, mode=image_mode)
  168. def get_size_with_aspect_ratio(image_size, size, max_size=None) -> tuple[int, int]:
  169. """
  170. Computes the output image size given the input image size and the desired output size.
  171. Args:
  172. image_size (`tuple[int, int]`):
  173. The input image size.
  174. size (`int`):
  175. The desired output size.
  176. max_size (`int`, *optional*):
  177. The maximum allowed output size.
  178. """
  179. height, width = image_size
  180. raw_size = None
  181. if max_size is not None:
  182. min_original_size = float(min((height, width)))
  183. max_original_size = float(max((height, width)))
  184. if max_original_size / min_original_size * size > max_size:
  185. raw_size = max_size * min_original_size / max_original_size
  186. size = int(round(raw_size))
  187. if (height <= width and height == size) or (width <= height and width == size):
  188. oh, ow = height, width
  189. elif width < height:
  190. ow = size
  191. if max_size is not None and raw_size is not None:
  192. oh = int(raw_size * height / width)
  193. else:
  194. oh = int(size * height / width)
  195. else:
  196. oh = size
  197. if max_size is not None and raw_size is not None:
  198. ow = int(raw_size * width / height)
  199. else:
  200. ow = int(size * width / height)
  201. return (oh, ow)
  202. # Logic adapted from torchvision resizing logic: https://github.com/pytorch/vision/blob/511924c1ced4ce0461197e5caa64ce5b9e558aab/torchvision/transforms/functional.py#L366
  203. def get_resize_output_image_size(
  204. input_image: np.ndarray,
  205. size: int | tuple[int, int] | list[int] | tuple[int, ...],
  206. default_to_square: bool = True,
  207. max_size: int | None = None,
  208. input_data_format: str | ChannelDimension | None = None,
  209. ) -> tuple:
  210. """
  211. Find the target (height, width) dimension of the output image after resizing given the input image and the desired
  212. size.
  213. Args:
  214. input_image (`np.ndarray`):
  215. The image to resize.
  216. size (`int` or `tuple[int, int]` or list[int] or `tuple[int]`):
  217. The size to use for resizing the image. If `size` is a sequence like (h, w), output size will be matched to
  218. this.
  219. If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If
  220. `size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to this
  221. number. i.e, if height > width, then image will be rescaled to (size * height / width, size).
  222. default_to_square (`bool`, *optional*, defaults to `True`):
  223. How to convert `size` when it is a single int. If set to `True`, the `size` will be converted to a square
  224. (`size`,`size`). If set to `False`, will replicate
  225. [`torchvision.transforms.Resize`](https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.Resize)
  226. with support for resizing only the smallest edge and providing an optional `max_size`.
  227. max_size (`int`, *optional*):
  228. The maximum allowed for the longer edge of the resized image: if the longer edge of the image is greater
  229. than `max_size` after being resized according to `size`, then the image is resized again so that the longer
  230. edge is equal to `max_size`. As a result, `size` might be overruled, i.e the smaller edge may be shorter
  231. than `size`. Only used if `default_to_square` is `False`.
  232. input_data_format (`ChannelDimension`, *optional*):
  233. The channel dimension format of the input image. If unset, will use the inferred format from the input.
  234. Returns:
  235. `tuple`: The target (height, width) dimension of the output image after resizing.
  236. """
  237. if isinstance(size, (tuple, list)):
  238. if len(size) == 2:
  239. return tuple(size)
  240. elif len(size) == 1:
  241. # Perform same logic as if size was an int
  242. size = size[0]
  243. else:
  244. raise ValueError("size must have 1 or 2 elements if it is a list or tuple")
  245. if default_to_square:
  246. return (size, size)
  247. height, width = get_image_size(input_image, input_data_format)
  248. short, long = (width, height) if width <= height else (height, width)
  249. requested_new_short = size
  250. new_short, new_long = requested_new_short, int(requested_new_short * long / short)
  251. if max_size is not None:
  252. if max_size <= requested_new_short:
  253. raise ValueError(
  254. f"max_size = {max_size} must be strictly greater than the requested "
  255. f"size for the smaller edge size = {size}"
  256. )
  257. if new_long > max_size:
  258. new_short, new_long = int(max_size * new_short / new_long), max_size
  259. return (new_long, new_short) if width <= height else (new_short, new_long)
  260. def resize(
  261. image: np.ndarray,
  262. size: tuple[int, int],
  263. resample: Optional["PILImageResampling"] = None,
  264. reducing_gap: int | None = None,
  265. data_format: ChannelDimension | None = None,
  266. return_numpy: bool = True,
  267. input_data_format: str | ChannelDimension | None = None,
  268. ) -> np.ndarray:
  269. """
  270. Resizes `image` to `(height, width)` specified by `size` using the PIL library.
  271. Args:
  272. image (`np.ndarray`):
  273. The image to resize.
  274. size (`tuple[int, int]`):
  275. The size to use for resizing the image.
  276. resample (`int`, *optional*, defaults to `PILImageResampling.BILINEAR`):
  277. The filter to user for resampling.
  278. reducing_gap (`int`, *optional*):
  279. Apply optimization by resizing the image in two steps. The bigger `reducing_gap`, the closer the result to
  280. the fair resampling. See corresponding Pillow documentation for more details.
  281. data_format (`ChannelDimension`, *optional*):
  282. The channel dimension format of the output image. If unset, will use the inferred format from the input.
  283. return_numpy (`bool`, *optional*, defaults to `True`):
  284. Whether or not to return the resized image as a numpy array. If False a `PIL.Image.Image` object is
  285. returned.
  286. input_data_format (`ChannelDimension`, *optional*):
  287. The channel dimension format of the input image. If unset, will use the inferred format from the input.
  288. Returns:
  289. `np.ndarray`: The resized image.
  290. """
  291. requires_backends(resize, ["vision"])
  292. resample = resample if resample is not None else PILImageResampling.BILINEAR
  293. if not len(size) == 2:
  294. raise ValueError("size must have 2 elements")
  295. # For all transformations, we want to keep the same data format as the input image unless otherwise specified.
  296. # The resized image from PIL will always have channels last, so find the input format first.
  297. if input_data_format is None:
  298. input_data_format = infer_channel_dimension_format(image)
  299. data_format = input_data_format if data_format is None else data_format
  300. # To maintain backwards compatibility with the resizing done in previous image feature extractors, we use
  301. # the pillow library to resize the image and then convert back to numpy
  302. do_rescale = False
  303. if not isinstance(image, PIL.Image.Image):
  304. do_rescale = _rescale_for_pil_conversion(image)
  305. image = to_pil_image(image, do_rescale=do_rescale, input_data_format=input_data_format)
  306. height, width = size
  307. # PIL images are in the format (width, height)
  308. resized_image = image.resize((width, height), resample=resample, reducing_gap=reducing_gap)
  309. if return_numpy:
  310. resized_image = np.array(resized_image)
  311. # If the input image channel dimension was of size 1, then it is dropped when converting to a PIL image
  312. # so we need to add it back if necessary.
  313. resized_image = np.expand_dims(resized_image, axis=-1) if resized_image.ndim == 2 else resized_image
  314. # The image is always in channels last format after converting from a PIL image
  315. resized_image = to_channel_dimension_format(
  316. resized_image, data_format, input_channel_dim=ChannelDimension.LAST
  317. )
  318. # If an image was rescaled to be in the range [0, 255] before converting to a PIL image, then we need to
  319. # rescale it back to the original range.
  320. resized_image = rescale(resized_image, 1 / 255) if do_rescale else resized_image
  321. return resized_image
  322. def normalize(
  323. image: np.ndarray,
  324. mean: float | Collection[float],
  325. std: float | Collection[float],
  326. data_format: ChannelDimension | None = None,
  327. input_data_format: str | ChannelDimension | None = None,
  328. ) -> np.ndarray:
  329. """
  330. Normalizes `image` using the mean and standard deviation specified by `mean` and `std`.
  331. image = (image - mean) / std
  332. Args:
  333. image (`np.ndarray`):
  334. The image to normalize.
  335. mean (`float` or `Collection[float]`):
  336. The mean to use for normalization.
  337. std (`float` or `Collection[float]`):
  338. The standard deviation to use for normalization.
  339. data_format (`ChannelDimension`, *optional*):
  340. The channel dimension format of the output image. If unset, will use the inferred format from the input.
  341. input_data_format (`ChannelDimension`, *optional*):
  342. The channel dimension format of the input image. If unset, will use the inferred format from the input.
  343. """
  344. if not isinstance(image, np.ndarray):
  345. raise TypeError("image must be a numpy array")
  346. if input_data_format is None:
  347. input_data_format = infer_channel_dimension_format(image)
  348. channel_axis = get_channel_dimension_axis(image, input_data_format=input_data_format)
  349. num_channels = image.shape[channel_axis]
  350. # We cast to float32 to avoid errors that can occur when subtracting uint8 values.
  351. # We preserve the original dtype if it is a float type to prevent upcasting float16.
  352. if not np.issubdtype(image.dtype, np.floating):
  353. image = image.astype(np.float32)
  354. if isinstance(mean, Collection):
  355. if len(mean) != num_channels:
  356. raise ValueError(f"mean must have {num_channels} elements if it is an iterable, got {len(mean)}")
  357. else:
  358. mean = [mean] * num_channels
  359. mean = np.array(mean, dtype=image.dtype)
  360. if isinstance(std, Collection):
  361. if len(std) != num_channels:
  362. raise ValueError(f"std must have {num_channels} elements if it is an iterable, got {len(std)}")
  363. else:
  364. std = [std] * num_channels
  365. std = np.array(std, dtype=image.dtype)
  366. if input_data_format == ChannelDimension.LAST:
  367. image = (image - mean) / std
  368. else:
  369. image = ((image.T - mean) / std).T
  370. image = to_channel_dimension_format(image, data_format, input_data_format) if data_format is not None else image
  371. return image
  372. def center_crop(
  373. image: np.ndarray,
  374. size: tuple[int, int],
  375. data_format: str | ChannelDimension | None = None,
  376. input_data_format: str | ChannelDimension | None = None,
  377. ) -> np.ndarray:
  378. """
  379. Crops the `image` to the specified `size` using a center crop. Note that if the image is too small to be cropped to
  380. the size given, it will be padded (so the returned result will always be of size `size`).
  381. Args:
  382. image (`np.ndarray`):
  383. The image to crop.
  384. size (`tuple[int, int]`):
  385. The target size for the cropped image.
  386. data_format (`str` or `ChannelDimension`, *optional*):
  387. The channel dimension format for the output image. Can be one of:
  388. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  389. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  390. If unset, will use the inferred format of the input image.
  391. input_data_format (`str` or `ChannelDimension`, *optional*):
  392. The channel dimension format for the input image. Can be one of:
  393. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  394. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  395. If unset, will use the inferred format of the input image.
  396. Returns:
  397. `np.ndarray`: The cropped image.
  398. """
  399. requires_backends(center_crop, ["vision"])
  400. if not isinstance(image, np.ndarray):
  401. raise TypeError(f"Input image must be of type np.ndarray, got {type(image)}")
  402. if not isinstance(size, Iterable) or len(size) != 2:
  403. raise ValueError("size must have 2 elements representing the height and width of the output image")
  404. if input_data_format is None:
  405. input_data_format = infer_channel_dimension_format(image)
  406. output_data_format = data_format if data_format is not None else input_data_format
  407. # We perform the crop in (C, H, W) format and then convert to the output format
  408. image = to_channel_dimension_format(image, ChannelDimension.FIRST, input_data_format)
  409. orig_height, orig_width = get_image_size(image, ChannelDimension.FIRST)
  410. crop_height, crop_width = size
  411. crop_height, crop_width = int(crop_height), int(crop_width)
  412. # In case size is odd, (image_shape[0] + size[0]) // 2 won't give the proper result.
  413. top = (orig_height - crop_height) // 2
  414. bottom = top + crop_height
  415. # In case size is odd, (image_shape[1] + size[1]) // 2 won't give the proper result.
  416. left = (orig_width - crop_width) // 2
  417. right = left + crop_width
  418. # Check if cropped area is within image boundaries
  419. if top >= 0 and bottom <= orig_height and left >= 0 and right <= orig_width:
  420. image = image[..., top:bottom, left:right]
  421. image = to_channel_dimension_format(image, output_data_format, ChannelDimension.FIRST)
  422. return image
  423. # Otherwise, we may need to pad if the image is too small. Oh joy...
  424. new_height = max(crop_height, orig_height)
  425. new_width = max(crop_width, orig_width)
  426. new_shape = image.shape[:-2] + (new_height, new_width)
  427. new_image = np.zeros_like(image, shape=new_shape)
  428. # If the image is too small, pad it with zeros
  429. top_pad = ceil((new_height - orig_height) / 2)
  430. bottom_pad = top_pad + orig_height
  431. left_pad = ceil((new_width - orig_width) / 2)
  432. right_pad = left_pad + orig_width
  433. new_image[..., top_pad:bottom_pad, left_pad:right_pad] = image
  434. top += top_pad
  435. bottom += top_pad
  436. left += left_pad
  437. right += left_pad
  438. new_image = new_image[..., max(0, top) : min(new_height, bottom), max(0, left) : min(new_width, right)]
  439. new_image = to_channel_dimension_format(new_image, output_data_format, ChannelDimension.FIRST)
  440. return new_image
  441. def _center_to_corners_format_torch(bboxes_center: "torch.Tensor") -> "torch.Tensor":
  442. center_x, center_y, width, height = bboxes_center.unbind(-1)
  443. bbox_corners = torch.stack(
  444. # top left x, top left y, bottom right x, bottom right y
  445. [(center_x - 0.5 * width), (center_y - 0.5 * height), (center_x + 0.5 * width), (center_y + 0.5 * height)],
  446. dim=-1,
  447. )
  448. return bbox_corners
  449. def _center_to_corners_format_numpy(bboxes_center: np.ndarray) -> np.ndarray:
  450. center_x, center_y, width, height = bboxes_center.T
  451. bboxes_corners = np.stack(
  452. # top left x, top left y, bottom right x, bottom right y
  453. [center_x - 0.5 * width, center_y - 0.5 * height, center_x + 0.5 * width, center_y + 0.5 * height],
  454. axis=-1,
  455. )
  456. return bboxes_corners
  457. # 2 functions below inspired by https://github.com/facebookresearch/detr/blob/master/util/box_ops.py
  458. def center_to_corners_format(bboxes_center: TensorType) -> TensorType:
  459. """
  460. Converts bounding boxes from center format to corners format.
  461. center format: contains the coordinate for the center of the box and its width, height dimensions
  462. (center_x, center_y, width, height)
  463. corners format: contains the coordinates for the top-left and bottom-right corners of the box
  464. (top_left_x, top_left_y, bottom_right_x, bottom_right_y)
  465. """
  466. # Function is used during model forward pass, so we use torch if relevant, without converting to numpy
  467. if is_torch_tensor(bboxes_center):
  468. return _center_to_corners_format_torch(bboxes_center)
  469. elif isinstance(bboxes_center, np.ndarray):
  470. return _center_to_corners_format_numpy(bboxes_center)
  471. raise ValueError(f"Unsupported input type {type(bboxes_center)}")
  472. def _corners_to_center_format_torch(bboxes_corners: "torch.Tensor") -> "torch.Tensor":
  473. top_left_x, top_left_y, bottom_right_x, bottom_right_y = bboxes_corners.unbind(-1)
  474. b = [
  475. (top_left_x + bottom_right_x) / 2, # center x
  476. (top_left_y + bottom_right_y) / 2, # center y
  477. (bottom_right_x - top_left_x), # width
  478. (bottom_right_y - top_left_y), # height
  479. ]
  480. return torch.stack(b, dim=-1)
  481. def _corners_to_center_format_numpy(bboxes_corners: np.ndarray) -> np.ndarray:
  482. top_left_x, top_left_y, bottom_right_x, bottom_right_y = bboxes_corners.T
  483. bboxes_center = np.stack(
  484. [
  485. (top_left_x + bottom_right_x) / 2, # center x
  486. (top_left_y + bottom_right_y) / 2, # center y
  487. (bottom_right_x - top_left_x), # width
  488. (bottom_right_y - top_left_y), # height
  489. ],
  490. axis=-1,
  491. )
  492. return bboxes_center
  493. def corners_to_center_format(bboxes_corners: TensorType) -> TensorType:
  494. """
  495. Converts bounding boxes from corners format to center format.
  496. corners format: contains the coordinates for the top-left and bottom-right corners of the box
  497. (top_left_x, top_left_y, bottom_right_x, bottom_right_y)
  498. center format: contains the coordinate for the center of the box and its the width, height dimensions
  499. (center_x, center_y, width, height)
  500. """
  501. # Inverse function accepts different input types so implemented here too
  502. if is_torch_tensor(bboxes_corners):
  503. return _corners_to_center_format_torch(bboxes_corners)
  504. elif isinstance(bboxes_corners, np.ndarray):
  505. return _corners_to_center_format_numpy(bboxes_corners)
  506. raise ValueError(f"Unsupported input type {type(bboxes_corners)}")
  507. def safe_squeeze(
  508. tensor: Union[np.ndarray, "torch.Tensor"], axis: int | None = None
  509. ) -> Union[np.ndarray, "torch.Tensor"]:
  510. """
  511. Squeezes a tensor, but only if the axis specified has dim 1.
  512. """
  513. if axis is None:
  514. return tensor.squeeze()
  515. try:
  516. return tensor.squeeze(axis=axis)
  517. except ValueError:
  518. return tensor
  519. # 2 functions below copied from https://github.com/cocodataset/panopticapi/blob/master/panopticapi/utils.py
  520. # Copyright (c) 2018, Alexander Kirillov
  521. # All rights reserved.
  522. def rgb_to_id(color):
  523. """
  524. Converts RGB color to unique ID.
  525. """
  526. if isinstance(color, np.ndarray) and len(color.shape) == 3:
  527. if color.dtype == np.uint8:
  528. color = color.astype(np.int32)
  529. return color[:, :, 0] + 256 * color[:, :, 1] + 256 * 256 * color[:, :, 2]
  530. return int(color[0] + 256 * color[1] + 256 * 256 * color[2])
  531. def id_to_rgb(id_map):
  532. """
  533. Converts unique ID to RGB color.
  534. """
  535. if isinstance(id_map, np.ndarray):
  536. id_map_copy = id_map.copy()
  537. rgb_shape = tuple(list(id_map.shape) + [3])
  538. rgb_map = np.zeros(rgb_shape, dtype=np.uint8)
  539. for i in range(3):
  540. rgb_map[..., i] = id_map_copy % 256
  541. id_map_copy //= 256
  542. return rgb_map
  543. color = []
  544. for _ in range(3):
  545. color.append(id_map % 256)
  546. id_map //= 256
  547. return color
  548. class PaddingMode(ExplicitEnum):
  549. """
  550. Enum class for the different padding modes to use when padding images.
  551. """
  552. CONSTANT = "constant"
  553. REFLECT = "reflect"
  554. REPLICATE = "replicate"
  555. SYMMETRIC = "symmetric"
  556. def pad(
  557. image: np.ndarray,
  558. padding: int | tuple[int, int] | Iterable[tuple[int, int]],
  559. mode: PaddingMode = PaddingMode.CONSTANT,
  560. constant_values: float | Iterable[float] = 0.0,
  561. data_format: str | ChannelDimension | None = None,
  562. input_data_format: str | ChannelDimension | None = None,
  563. ) -> np.ndarray:
  564. """
  565. Pads the `image` with the specified (height, width) `padding` and `mode`.
  566. Args:
  567. image (`np.ndarray`):
  568. The image to pad.
  569. padding (`int` or `tuple[int, int]` or `Iterable[tuple[int, int]]`):
  570. Padding to apply to the edges of the height, width axes. Can be one of three formats:
  571. - `((before_height, after_height), (before_width, after_width))` unique pad widths for each axis.
  572. - `((before, after),)` yields same before and after pad for height and width.
  573. - `(pad,)` or int is a shortcut for before = after = pad width for all axes.
  574. mode (`PaddingMode`):
  575. The padding mode to use. Can be one of:
  576. - `"constant"`: pads with a constant value.
  577. - `"reflect"`: pads with the reflection of the vector mirrored on the first and last values of the
  578. vector along each axis.
  579. - `"replicate"`: pads with the replication of the last value on the edge of the array along each axis.
  580. - `"symmetric"`: pads with the reflection of the vector mirrored along the edge of the array.
  581. constant_values (`float` or `Iterable[float]`, *optional*):
  582. The value to use for the padding if `mode` is `"constant"`.
  583. data_format (`str` or `ChannelDimension`, *optional*):
  584. The channel dimension format for the output image. Can be one of:
  585. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  586. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  587. If unset, will use same as the input image.
  588. input_data_format (`str` or `ChannelDimension`, *optional*):
  589. The channel dimension format for the input image. Can be one of:
  590. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  591. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  592. If unset, will use the inferred format of the input image.
  593. Returns:
  594. `np.ndarray`: The padded image.
  595. """
  596. if input_data_format is None:
  597. input_data_format = infer_channel_dimension_format(image)
  598. def _expand_for_data_format(values):
  599. """
  600. Convert values to be in the format expected by np.pad based on the data format.
  601. """
  602. if isinstance(values, (int, float)):
  603. values = ((values, values), (values, values))
  604. elif isinstance(values, tuple) and len(values) == 1:
  605. values = ((values[0], values[0]), (values[0], values[0]))
  606. elif isinstance(values, tuple) and len(values) == 2 and isinstance(values[0], int):
  607. values = (values, values)
  608. elif isinstance(values, tuple) and len(values) == 2 and isinstance(values[0], tuple):
  609. pass
  610. else:
  611. raise ValueError(f"Unsupported format: {values}")
  612. # add 0 for channel dimension
  613. values = ((0, 0), *values) if input_data_format == ChannelDimension.FIRST else (*values, (0, 0))
  614. # Add additional padding if there's a batch dimension
  615. values = ((0, 0), *values) if image.ndim == 4 else values
  616. return values
  617. padding = _expand_for_data_format(padding)
  618. if mode == PaddingMode.CONSTANT:
  619. constant_values = _expand_for_data_format(constant_values)
  620. image = np.pad(image, padding, mode="constant", constant_values=constant_values)
  621. elif mode == PaddingMode.REFLECT:
  622. image = np.pad(image, padding, mode="reflect")
  623. elif mode == PaddingMode.REPLICATE:
  624. image = np.pad(image, padding, mode="edge")
  625. elif mode == PaddingMode.SYMMETRIC:
  626. image = np.pad(image, padding, mode="symmetric")
  627. else:
  628. raise ValueError(f"Invalid padding mode: {mode}")
  629. image = to_channel_dimension_format(image, data_format, input_data_format) if data_format is not None else image
  630. return image
  631. # TODO (Amy): Accept 1/3/4 channel numpy array as input and return np.array as default
  632. def convert_to_rgb(image: ImageInput) -> ImageInput:
  633. """
  634. Converts an image to RGB format. Only converts if the image is of type PIL.Image.Image, otherwise returns the image
  635. as is.
  636. Args:
  637. image (Image):
  638. The image to convert.
  639. """
  640. requires_backends(convert_to_rgb, ["vision"])
  641. if not isinstance(image, PIL.Image.Image):
  642. return image
  643. if image.mode == "RGB":
  644. return image
  645. image = image.convert("RGB")
  646. return image
  647. def flip_channel_order(
  648. image: np.ndarray,
  649. data_format: ChannelDimension | None = None,
  650. input_data_format: str | ChannelDimension | None = None,
  651. ) -> np.ndarray:
  652. """
  653. Flips the channel order of the image.
  654. If the image is in RGB format, it will be converted to BGR and vice versa.
  655. Args:
  656. image (`np.ndarray`):
  657. The image to flip.
  658. data_format (`ChannelDimension`, *optional*):
  659. The channel dimension format for the output image. Can be one of:
  660. - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  661. - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  662. If unset, will use same as the input image.
  663. input_data_format (`ChannelDimension`, *optional*):
  664. The channel dimension format for the input image. Can be one of:
  665. - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  666. - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  667. If unset, will use the inferred format of the input image.
  668. """
  669. input_data_format = infer_channel_dimension_format(image) if input_data_format is None else input_data_format
  670. if input_data_format == ChannelDimension.LAST:
  671. image = image[..., ::-1]
  672. elif input_data_format == ChannelDimension.FIRST:
  673. image = image[::-1, ...]
  674. else:
  675. raise ValueError(f"Unsupported channel dimension: {input_data_format}")
  676. if data_format is not None:
  677. image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
  678. return image
  679. def split_to_tiles(images: "torch.Tensor", num_tiles_height: int, num_tiles_width: int) -> "torch.Tensor":
  680. # Split image into number of required tiles (width x height)
  681. batch_size, num_channels, height, width = images.size()
  682. images = images.view(
  683. batch_size,
  684. num_channels,
  685. num_tiles_height,
  686. height // num_tiles_height,
  687. num_tiles_width,
  688. width // num_tiles_width,
  689. )
  690. # Permute dimensions to reorder the axes
  691. image = images.permute(0, 2, 4, 1, 3, 5).contiguous()
  692. # Reshape into the desired output shape (batch_size * 4, num_channels, width/2, height/2)
  693. image = image.view(
  694. batch_size,
  695. num_tiles_width * num_tiles_height,
  696. num_channels,
  697. height // num_tiles_height,
  698. width // num_tiles_width,
  699. )
  700. return image
  701. def divide_to_patches(
  702. image: Union[np.ndarray, "torch.Tensor"], patch_size: int
  703. ) -> list[Union[np.ndarray, "torch.Tensor"]]:
  704. """
  705. Divides an image into patches of a specified size.
  706. Args:
  707. image (`np.array | "torch.Tensor"`):
  708. The input image.
  709. patch_size (`int`):
  710. The size of each patch.
  711. Returns:
  712. list: A list of `np.array | "torch.Tensor"` representing the patches.
  713. """
  714. patches = []
  715. height, width = get_image_size(image, channel_dim=ChannelDimension.FIRST)
  716. for i in range(0, height, patch_size):
  717. for j in range(0, width, patch_size):
  718. patch = image[:, i : i + patch_size, j : j + patch_size]
  719. patches.append(patch)
  720. return patches
  721. def _group_images_by_shape(nested_images, *paired_inputs, is_nested: bool = False):
  722. """
  723. Helper function to flatten a single level of nested image and batch structures and group by shape.
  724. Args:
  725. nested_images (list):
  726. A list of images or a single tensor
  727. paired_inputs (Any, *optional*):
  728. Zero or more lists that mirror the structure of `nested_images` (flat list, or list of lists when
  729. `is_nested=True`). Each element is paired 1:1 with the corresponding image so it can be grouped by the
  730. same shape key. These paired values are grouped alongside `nested_images` but are not stacked in the output, so
  731. they do not need to be tensors.
  732. is_nested (bool, *optional*, defaults to False):
  733. Whether the images are nested.
  734. Returns:
  735. tuple[dict, ...]:
  736. - A dictionary with shape as key and list of images with that shape as value
  737. - A dictionary with shape as key and list of paired values with that shape as value
  738. - A dictionary mapping original indices to (shape, index) tuples
  739. - A dictionary mapping original indices to (shape, index) tuples for each paired input
  740. """
  741. grouped_images = defaultdict(list)
  742. grouped_images_index = {}
  743. paired_grouped_values = [defaultdict(list) for _ in paired_inputs]
  744. # Normalize inputs to consistent nested structure
  745. normalized_images = [nested_images] if not is_nested else nested_images
  746. normalized_paired = []
  747. for paired_input in paired_inputs:
  748. normalized_paired.append([paired_input] if not is_nested else paired_input)
  749. # Process each image and group by shape
  750. for i, (sublist, *paired_sublists) in enumerate(zip(normalized_images, *normalized_paired)):
  751. for j, (image, *paired_values) in enumerate(zip(sublist, *paired_sublists)):
  752. key = (i, j) if is_nested else j
  753. shape = image.shape[1:]
  754. # Add to grouped structures
  755. grouped_images[shape].append(image)
  756. for paired_index, paired_value in enumerate(paired_values):
  757. paired_grouped_values[paired_index][shape].append(paired_value)
  758. grouped_images_index[key] = (shape, len(grouped_images[shape]) - 1)
  759. # Store structure size for nested inputs to handle empty sublists during reconstruction
  760. if is_nested:
  761. grouped_images_index["_num_sublists"] = len(normalized_images)
  762. return grouped_images, *paired_grouped_values, grouped_images_index
  763. def _reconstruct_nested_structure(indices, processed_images):
  764. """Helper function to reconstruct a single level nested structure."""
  765. # Get the number of sublists (handles empty sublists like in [[], [image]])
  766. num_sublists = indices.pop("_num_sublists", None)
  767. # Group indices by outer index
  768. nested_indices = defaultdict(list)
  769. for i, j in indices:
  770. nested_indices[i].append(j)
  771. # Determine the number of outer sublists
  772. if num_sublists is not None:
  773. max_outer_idx = num_sublists - 1
  774. elif nested_indices:
  775. max_outer_idx = max(nested_indices.keys())
  776. else:
  777. return []
  778. # Create the result structure
  779. result = []
  780. for i in range(max_outer_idx + 1):
  781. if i not in nested_indices:
  782. result.append([])
  783. else:
  784. inner_max_idx = max(nested_indices[i])
  785. inner_list = [None] * (inner_max_idx + 1)
  786. for j in nested_indices[i]:
  787. shape, idx = indices[(i, j)]
  788. inner_list[j] = processed_images[shape][idx]
  789. result.append(inner_list)
  790. return result
  791. def _iterate_items(items, is_nested: bool):
  792. """
  793. Helper function to iterate over items yielding (key, item) pairs.
  794. For nested structures, yields ((row_index, col_index), item).
  795. For flat structures, yields (index, item).
  796. """
  797. if is_nested:
  798. for i, row in enumerate(items):
  799. for j, item in enumerate(row):
  800. yield (i, j), item
  801. else:
  802. for i, item in enumerate(items):
  803. yield i, item
  804. def _get_device_from_images(images, is_nested: bool) -> "torch.device":
  805. """
  806. Get the device from the first non-empty element in a (potentially nested) list of images.
  807. Handles cases like `images = [[], [image]]` where the first sublist may be empty.
  808. """
  809. if is_nested:
  810. for row in images:
  811. if isinstance(row, torch.Tensor):
  812. return row.device
  813. if isinstance(row, list) and len(row) > 0:
  814. return row[0].device
  815. return images[0].device
  816. def group_images_by_shape(
  817. images: Union[list["torch.Tensor"], "torch.Tensor"],
  818. *paired_inputs,
  819. disable_grouping: bool | None,
  820. is_nested: bool = False,
  821. ) -> tuple[dict, ...]:
  822. """
  823. Groups images by shape.
  824. Returns a dictionary with the shape as key and a list of images with that shape as value,
  825. and a dictionary with the index of the image in the original list as key and the shape and index in the grouped list as value.
  826. The function supports both flat lists of tensors and nested structures.
  827. The input must be either all flat or all nested, not a mix of both.
  828. Args:
  829. images (Union[list["torch.Tensor"], "torch.Tensor"]):
  830. A list of images or a single tensor
  831. paired_inputs (Any, *optional*):
  832. Zero or more lists that mirror the structure of `images` (flat list, or list of lists when
  833. `is_nested=True`). Each element is paired 1:1 with the corresponding image so it can be grouped by the
  834. same shape key. These paired values are grouped alongside `images` but are not stacked in the output, so
  835. they do not need to be tensors.
  836. disable_grouping (bool):
  837. Whether to disable grouping. If None, will be set to True if the images are on CPU, and False otherwise.
  838. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157
  839. is_nested (bool, *optional*, defaults to False):
  840. Whether the images are nested.
  841. Returns:
  842. tuple[dict, ...]:
  843. - A dictionary with shape as key and list/batch of images with that shape as value
  844. - Zero or more dictionaries (one per argument in `*paired_inputs`) grouped consistently with `images`; these carry
  845. the corresponding per-item values and are not stacked
  846. - A dictionary mapping original indices to (shape, index) tuples
  847. """
  848. # If disable grouping is not explicitly provided, we favor disabling it if the images are on CPU, and enabling it otherwise.
  849. if disable_grouping is None:
  850. device = _get_device_from_images(images, is_nested)
  851. disable_grouping = device == "cpu"
  852. if disable_grouping:
  853. grouped_images_index = {key: (key, 0) for key, _ in _iterate_items(images, is_nested)}
  854. if is_nested:
  855. grouped_images_index["_num_sublists"] = len(images)
  856. return (
  857. {key: img.unsqueeze(0) for key, img in _iterate_items(images, is_nested)},
  858. *[
  859. {key: item.unsqueeze(0) for key, item in _iterate_items(paired_list, is_nested)}
  860. for paired_list in paired_inputs
  861. ],
  862. grouped_images_index,
  863. )
  864. # Handle single level nested structure
  865. grouped_images, *paired_grouped_values, grouped_images_index = _group_images_by_shape(
  866. images, *paired_inputs, is_nested=is_nested
  867. )
  868. # Stack images with the same shape
  869. grouped_images = {shape: torch.stack(images_list, dim=0) for shape, images_list in grouped_images.items()}
  870. return grouped_images, *paired_grouped_values, grouped_images_index
  871. def reorder_images(
  872. processed_images: dict[tuple[int, int], "torch.Tensor"],
  873. grouped_images_index: dict[int | tuple[int, int], tuple[tuple[int, int], int]],
  874. is_nested: bool = False,
  875. ) -> Union[list["torch.Tensor"], "torch.Tensor"]:
  876. """
  877. Reconstructs images in the original order, preserving the original structure (nested or not).
  878. The input structure is either all flat or all nested.
  879. Args:
  880. processed_images (dict[tuple[int, int], "torch.Tensor"]):
  881. Dictionary mapping shapes to batched processed images.
  882. grouped_images_index (dict[Union[int, tuple[int, int]], tuple[tuple[int, int], int]]):
  883. Dictionary mapping original indices to (shape, index) tuples.
  884. is_nested (bool, *optional*, defaults to False):
  885. Whether the images are nested. Cannot be inferred from the input, as some processing functions outputs nested images.
  886. even with non nested images,e.g functions splitting images into patches. We thus can't deduce is_nested from the input.
  887. Returns:
  888. Union[list["torch.Tensor"], "torch.Tensor"]:
  889. Images in the original structure.
  890. """
  891. if not is_nested:
  892. return [
  893. processed_images[grouped_images_index[i][0]][grouped_images_index[i][1]]
  894. for i in range(len(grouped_images_index))
  895. ]
  896. return _reconstruct_nested_structure(grouped_images_index, processed_images)