image_processing_tvp.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. # coding=utf-8
  2. # Copyright 2023 The Intel AIA Team Authors, and HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License=, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing=, software
  11. # distributed under the License is distributed on an "AS IS" BASIS=,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND=, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Image processor class for TVP."""
  16. from typing import Dict, Iterable, List, Optional, Tuple, Union
  17. import numpy as np
  18. from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
  19. from ...image_transforms import (
  20. PaddingMode,
  21. flip_channel_order,
  22. pad,
  23. resize,
  24. to_channel_dimension_format,
  25. )
  26. from ...image_utils import (
  27. IMAGENET_STANDARD_MEAN,
  28. IMAGENET_STANDARD_STD,
  29. ChannelDimension,
  30. ImageInput,
  31. PILImageResampling,
  32. get_image_size,
  33. is_valid_image,
  34. to_numpy_array,
  35. valid_images,
  36. validate_preprocess_arguments,
  37. )
  38. from ...utils import TensorType, filter_out_non_signature_kwargs, is_vision_available, logging
  39. if is_vision_available():
  40. import PIL
  41. logger = logging.get_logger(__name__)
  42. # Copied from transformers.models.vivit.image_processing_vivit.make_batched
  43. def make_batched(videos) -> List[List[ImageInput]]:
  44. if isinstance(videos, (list, tuple)) and isinstance(videos[0], (list, tuple)) and is_valid_image(videos[0][0]):
  45. return videos
  46. elif isinstance(videos, (list, tuple)) and is_valid_image(videos[0]):
  47. return [videos]
  48. elif is_valid_image(videos):
  49. return [[videos]]
  50. raise ValueError(f"Could not make batched video from {videos}")
  51. def get_resize_output_image_size(
  52. input_image: np.ndarray,
  53. max_size: int = 448,
  54. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  55. ) -> Tuple[int, int]:
  56. height, width = get_image_size(input_image, input_data_format)
  57. if height >= width:
  58. ratio = width * 1.0 / height
  59. new_height = max_size
  60. new_width = new_height * ratio
  61. else:
  62. ratio = height * 1.0 / width
  63. new_width = max_size
  64. new_height = new_width * ratio
  65. size = (int(new_height), int(new_width))
  66. return size
  67. class TvpImageProcessor(BaseImageProcessor):
  68. r"""
  69. Constructs a Tvp image processor.
  70. Args:
  71. do_resize (`bool`, *optional*, defaults to `True`):
  72. Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
  73. `do_resize` parameter in the `preprocess` method.
  74. size (`Dict[str, int]` *optional*, defaults to `{"longest_edge": 448}`):
  75. Size of the output image after resizing. The longest edge of the image will be resized to
  76. `size["longest_edge"]` while maintaining the aspect ratio of the original image. Can be overriden by
  77. `size` in the `preprocess` method.
  78. resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
  79. Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
  80. `preprocess` method.
  81. do_center_crop (`bool`, *optional*, defaults to `True`):
  82. Whether to center crop the image to the specified `crop_size`. Can be overridden by the `do_center_crop`
  83. parameter in the `preprocess` method.
  84. crop_size (`Dict[str, int]`, *optional*, defaults to `{"height": 448, "width": 448}`):
  85. Size of the image after applying the center crop. Can be overridden by the `crop_size` parameter in the
  86. `preprocess` method.
  87. do_rescale (`bool`, *optional*, defaults to `True`):
  88. Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
  89. parameter in the `preprocess` method.
  90. rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
  91. Defines the scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter
  92. in the `preprocess` method.
  93. do_pad (`bool`, *optional*, defaults to `True`):
  94. Whether to pad the image. Can be overridden by the `do_pad` parameter in the `preprocess` method.
  95. pad_size (`Dict[str, int]`, *optional*, defaults to `{"height": 448, "width": 448}`):
  96. Size of the image after applying the padding. Can be overridden by the `pad_size` parameter in the
  97. `preprocess` method.
  98. constant_values (`Union[float, Iterable[float]]`, *optional*, defaults to 0):
  99. The fill value to use when padding the image.
  100. pad_mode (`PaddingMode`, *optional*, defaults to `PaddingMode.CONSTANT`):
  101. Use what kind of mode in padding.
  102. do_normalize (`bool`, *optional*, defaults to `True`):
  103. Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
  104. method.
  105. do_flip_channel_order (`bool`, *optional*, defaults to `True`):
  106. Whether to flip the color channels from RGB to BGR. Can be overridden by the `do_flip_channel_order`
  107. parameter in the `preprocess` method.
  108. image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
  109. Mean to use if normalizing the image. This is a float or list of floats the length of the number of
  110. channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
  111. image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
  112. Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
  113. number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
  114. """
  115. model_input_names = ["pixel_values"]
  116. def __init__(
  117. self,
  118. do_resize: bool = True,
  119. size: Dict[str, int] = None,
  120. resample: PILImageResampling = PILImageResampling.BILINEAR,
  121. do_center_crop: bool = True,
  122. crop_size: Dict[str, int] = None,
  123. do_rescale: bool = True,
  124. rescale_factor: Union[int, float] = 1 / 255,
  125. do_pad: bool = True,
  126. pad_size: Dict[str, int] = None,
  127. constant_values: Union[float, Iterable[float]] = 0,
  128. pad_mode: PaddingMode = PaddingMode.CONSTANT,
  129. do_normalize: bool = True,
  130. do_flip_channel_order: bool = True,
  131. image_mean: Optional[Union[float, List[float]]] = None,
  132. image_std: Optional[Union[float, List[float]]] = None,
  133. **kwargs,
  134. ) -> None:
  135. super().__init__(**kwargs)
  136. size = size if size is not None else {"longest_edge": 448}
  137. crop_size = crop_size if crop_size is not None else {"height": 448, "width": 448}
  138. pad_size = pad_size if pad_size is not None else {"height": 448, "width": 448}
  139. self.do_resize = do_resize
  140. self.size = size
  141. self.do_center_crop = do_center_crop
  142. self.crop_size = crop_size
  143. self.resample = resample
  144. self.do_rescale = do_rescale
  145. self.rescale_factor = rescale_factor
  146. self.do_pad = do_pad
  147. self.pad_size = pad_size
  148. self.constant_values = constant_values
  149. self.pad_mode = pad_mode
  150. self.do_normalize = do_normalize
  151. self.do_flip_channel_order = do_flip_channel_order
  152. self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
  153. self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
  154. def resize(
  155. self,
  156. image: np.ndarray,
  157. size: Dict[str, int],
  158. resample: PILImageResampling = PILImageResampling.BILINEAR,
  159. data_format: Optional[Union[str, ChannelDimension]] = None,
  160. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  161. **kwargs,
  162. ) -> np.ndarray:
  163. """
  164. Resize an image.
  165. Args:
  166. image (`np.ndarray`):
  167. Image to resize.
  168. size (`Dict[str, int]`):
  169. Size of the output image. If `size` is of the form `{"height": h, "width": w}`, the output image will
  170. have the size `(h, w)`. If `size` is of the form `{"longest_edge": s}`, the output image will have its
  171. longest edge of length `s` while keeping the aspect ratio of the original image.
  172. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
  173. Resampling filter to use when resiizing the image.
  174. data_format (`str` or `ChannelDimension`, *optional*):
  175. The channel dimension format of the image. If not provided, it will be the same as the input image.
  176. input_data_format (`str` or `ChannelDimension`, *optional*):
  177. The channel dimension format of the input image. If not provided, it will be inferred.
  178. """
  179. size = get_size_dict(size, default_to_square=False)
  180. if "height" in size and "width" in size:
  181. output_size = (size["height"], size["width"])
  182. elif "longest_edge" in size:
  183. output_size = get_resize_output_image_size(image, size["longest_edge"], input_data_format)
  184. else:
  185. raise ValueError(f"Size must have 'height' and 'width' or 'longest_edge' as keys. Got {size.keys()}")
  186. return resize(
  187. image,
  188. size=output_size,
  189. resample=resample,
  190. data_format=data_format,
  191. input_data_format=input_data_format,
  192. **kwargs,
  193. )
  194. def pad_image(
  195. self,
  196. image: np.ndarray,
  197. pad_size: Dict[str, int] = None,
  198. constant_values: Union[float, Iterable[float]] = 0,
  199. pad_mode: PaddingMode = PaddingMode.CONSTANT,
  200. data_format: Optional[Union[str, ChannelDimension]] = None,
  201. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  202. **kwargs,
  203. ):
  204. """
  205. Pad an image with zeros to the given size.
  206. Args:
  207. image (`np.ndarray`):
  208. Image to pad.
  209. pad_size (`Dict[str, int]`)
  210. Size of the output image with pad.
  211. constant_values (`Union[float, Iterable[float]]`)
  212. The fill value to use when padding the image.
  213. pad_mode (`PaddingMode`)
  214. The pad mode, default to PaddingMode.CONSTANT
  215. data_format (`ChannelDimension` or `str`, *optional*)
  216. The channel dimension format of the image. If not provided, it will be the same as the input image.
  217. input_data_format (`ChannelDimension` or `str`, *optional*):
  218. The channel dimension format of the input image. If not provided, it will be inferred.
  219. """
  220. height, width = get_image_size(image, channel_dim=input_data_format)
  221. max_height = pad_size.get("height", height)
  222. max_width = pad_size.get("width", width)
  223. pad_right, pad_bottom = max_width - width, max_height - height
  224. if pad_right < 0 or pad_bottom < 0:
  225. raise ValueError("The padding size must be greater than image size")
  226. padding = ((0, pad_bottom), (0, pad_right))
  227. padded_image = pad(
  228. image,
  229. padding,
  230. mode=pad_mode,
  231. constant_values=constant_values,
  232. data_format=data_format,
  233. input_data_format=input_data_format,
  234. )
  235. return padded_image
  236. def _preprocess_image(
  237. self,
  238. image: ImageInput,
  239. do_resize: bool = None,
  240. size: Dict[str, int] = None,
  241. resample: PILImageResampling = None,
  242. do_center_crop: bool = None,
  243. crop_size: Dict[str, int] = None,
  244. do_rescale: bool = None,
  245. rescale_factor: float = None,
  246. do_pad: bool = True,
  247. pad_size: Dict[str, int] = None,
  248. constant_values: Union[float, Iterable[float]] = None,
  249. pad_mode: PaddingMode = None,
  250. do_normalize: bool = None,
  251. do_flip_channel_order: bool = None,
  252. image_mean: Optional[Union[float, List[float]]] = None,
  253. image_std: Optional[Union[float, List[float]]] = None,
  254. data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
  255. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  256. **kwargs,
  257. ) -> np.ndarray:
  258. """Preprocesses a single image."""
  259. validate_preprocess_arguments(
  260. do_rescale=do_rescale,
  261. rescale_factor=rescale_factor,
  262. do_normalize=do_normalize,
  263. image_mean=image_mean,
  264. image_std=image_std,
  265. do_pad=do_pad,
  266. size_divisibility=pad_size, # here the pad() method simply requires the pad_size argument.
  267. do_center_crop=do_center_crop,
  268. crop_size=crop_size,
  269. do_resize=do_resize,
  270. size=size,
  271. resample=resample,
  272. )
  273. # All transformations expect numpy arrays.
  274. image = to_numpy_array(image)
  275. if do_resize:
  276. image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
  277. if do_center_crop:
  278. image = self.center_crop(image, size=crop_size, input_data_format=input_data_format)
  279. if do_rescale:
  280. image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
  281. if do_normalize:
  282. image = self.normalize(
  283. image=image.astype(np.float32), mean=image_mean, std=image_std, input_data_format=input_data_format
  284. )
  285. if do_pad:
  286. image = self.pad_image(
  287. image=image,
  288. pad_size=pad_size,
  289. constant_values=constant_values,
  290. pad_mode=pad_mode,
  291. input_data_format=input_data_format,
  292. )
  293. # the pretrained checkpoints assume images are BGR, not RGB
  294. if do_flip_channel_order:
  295. image = flip_channel_order(image=image, input_data_format=input_data_format)
  296. image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
  297. return image
  298. @filter_out_non_signature_kwargs()
  299. def preprocess(
  300. self,
  301. videos: Union[ImageInput, List[ImageInput], List[List[ImageInput]]],
  302. do_resize: bool = None,
  303. size: Dict[str, int] = None,
  304. resample: PILImageResampling = None,
  305. do_center_crop: bool = None,
  306. crop_size: Dict[str, int] = None,
  307. do_rescale: bool = None,
  308. rescale_factor: float = None,
  309. do_pad: bool = None,
  310. pad_size: Dict[str, int] = None,
  311. constant_values: Union[float, Iterable[float]] = None,
  312. pad_mode: PaddingMode = None,
  313. do_normalize: bool = None,
  314. do_flip_channel_order: bool = None,
  315. image_mean: Optional[Union[float, List[float]]] = None,
  316. image_std: Optional[Union[float, List[float]]] = None,
  317. return_tensors: Optional[Union[str, TensorType]] = None,
  318. data_format: ChannelDimension = ChannelDimension.FIRST,
  319. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  320. ) -> PIL.Image.Image:
  321. """
  322. Preprocess an image or batch of images.
  323. Args:
  324. videos (`ImageInput` or `List[ImageInput]` or `List[List[ImageInput]]`):
  325. Frames to preprocess.
  326. do_resize (`bool`, *optional*, defaults to `self.do_resize`):
  327. Whether to resize the image.
  328. size (`Dict[str, int]`, *optional*, defaults to `self.size`):
  329. Size of the image after applying resize.
  330. resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
  331. Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only
  332. has an effect if `do_resize` is set to `True`.
  333. do_center_crop (`bool`, *optional*, defaults to `self.do_centre_crop`):
  334. Whether to centre crop the image.
  335. crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
  336. Size of the image after applying the centre crop.
  337. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
  338. Whether to rescale the image values between [0 - 1].
  339. rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
  340. Rescale factor to rescale the image by if `do_rescale` is set to `True`.
  341. do_pad (`bool`, *optional*, defaults to `True`):
  342. Whether to pad the image. Can be overridden by the `do_pad` parameter in the `preprocess` method.
  343. pad_size (`Dict[str, int]`, *optional*, defaults to `{"height": 448, "width": 448}`):
  344. Size of the image after applying the padding. Can be overridden by the `pad_size` parameter in the
  345. `preprocess` method.
  346. constant_values (`Union[float, Iterable[float]]`, *optional*, defaults to 0):
  347. The fill value to use when padding the image.
  348. pad_mode (`PaddingMode`, *optional*, defaults to "PaddingMode.CONSTANT"):
  349. Use what kind of mode in padding.
  350. do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
  351. Whether to normalize the image.
  352. do_flip_channel_order (`bool`, *optional*, defaults to `self.do_flip_channel_order`):
  353. Whether to flip the channel order of the image.
  354. image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
  355. Image mean.
  356. image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
  357. Image standard deviation.
  358. return_tensors (`str` or `TensorType`, *optional*):
  359. The type of tensors to return. Can be one of:
  360. - Unset: Return a list of `np.ndarray`.
  361. - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
  362. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
  363. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
  364. - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
  365. data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
  366. The channel dimension format for the output image. Can be one of:
  367. - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  368. - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  369. - Unset: Use the inferred channel dimension format of the input image.
  370. input_data_format (`ChannelDimension` or `str`, *optional*):
  371. The channel dimension format for the input image. If unset, the channel dimension format is inferred
  372. from the input image. Can be one of:
  373. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  374. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  375. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  376. """
  377. do_resize = do_resize if do_resize is not None else self.do_resize
  378. resample = resample if resample is not None else self.resample
  379. do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
  380. do_rescale = do_rescale if do_rescale is not None else self.do_rescale
  381. rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
  382. do_pad = do_pad if do_pad is not None else self.do_pad
  383. pad_size = pad_size if pad_size is not None else self.pad_size
  384. constant_values = constant_values if constant_values is not None else self.constant_values
  385. pad_mode = pad_mode if pad_mode else self.pad_mode
  386. do_normalize = do_normalize if do_normalize is not None else self.do_normalize
  387. do_flip_channel_order = (
  388. do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order
  389. )
  390. image_mean = image_mean if image_mean is not None else self.image_mean
  391. image_std = image_std if image_std is not None else self.image_std
  392. size = size if size is not None else self.size
  393. size = get_size_dict(size, default_to_square=False)
  394. crop_size = crop_size if crop_size is not None else self.crop_size
  395. crop_size = get_size_dict(crop_size, param_name="crop_size")
  396. if not valid_images(videos):
  397. raise ValueError(
  398. "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
  399. "torch.Tensor, tf.Tensor or jax.ndarray."
  400. )
  401. videos = make_batched(videos)
  402. videos = [
  403. np.array(
  404. [
  405. self._preprocess_image(
  406. image=img,
  407. do_resize=do_resize,
  408. size=size,
  409. resample=resample,
  410. do_center_crop=do_center_crop,
  411. crop_size=crop_size,
  412. do_rescale=do_rescale,
  413. rescale_factor=rescale_factor,
  414. do_pad=do_pad,
  415. pad_size=pad_size,
  416. constant_values=constant_values,
  417. pad_mode=pad_mode,
  418. do_normalize=do_normalize,
  419. do_flip_channel_order=do_flip_channel_order,
  420. image_mean=image_mean,
  421. image_std=image_std,
  422. data_format=data_format,
  423. input_data_format=input_data_format,
  424. )
  425. for img in video
  426. ]
  427. )
  428. for video in videos
  429. ]
  430. data = {"pixel_values": videos}
  431. return BatchFeature(data=data, tensor_type=return_tensors)