image_transforms.py 41 KB

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