image_processing_vivit.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. # coding=utf-8
  2. # Copyright 2023 The HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Image processor class for Vivit."""
  16. from typing import Dict, List, Optional, Union
  17. import numpy as np
  18. from transformers.utils import is_vision_available
  19. from transformers.utils.generic import TensorType
  20. from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
  21. from ...image_transforms import (
  22. get_resize_output_image_size,
  23. rescale,
  24. resize,
  25. to_channel_dimension_format,
  26. )
  27. from ...image_utils import (
  28. IMAGENET_STANDARD_MEAN,
  29. IMAGENET_STANDARD_STD,
  30. ChannelDimension,
  31. ImageInput,
  32. PILImageResampling,
  33. infer_channel_dimension_format,
  34. is_scaled_image,
  35. is_valid_image,
  36. to_numpy_array,
  37. valid_images,
  38. validate_preprocess_arguments,
  39. )
  40. from ...utils import filter_out_non_signature_kwargs, logging
  41. if is_vision_available():
  42. import PIL
  43. logger = logging.get_logger(__name__)
  44. def make_batched(videos) -> List[List[ImageInput]]:
  45. if isinstance(videos, (list, tuple)) and isinstance(videos[0], (list, tuple)) and is_valid_image(videos[0][0]):
  46. return videos
  47. elif isinstance(videos, (list, tuple)) and is_valid_image(videos[0]):
  48. return [videos]
  49. elif is_valid_image(videos):
  50. return [[videos]]
  51. raise ValueError(f"Could not make batched video from {videos}")
  52. class VivitImageProcessor(BaseImageProcessor):
  53. r"""
  54. Constructs a Vivit image processor.
  55. Args:
  56. do_resize (`bool`, *optional*, defaults to `True`):
  57. Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
  58. `do_resize` parameter in the `preprocess` method.
  59. size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 256}`):
  60. Size of the output image after resizing. The shortest edge of the image will be resized to
  61. `size["shortest_edge"]` while maintaining the aspect ratio of the original image. Can be overriden by
  62. `size` in the `preprocess` method.
  63. resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
  64. Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
  65. `preprocess` method.
  66. do_center_crop (`bool`, *optional*, defaults to `True`):
  67. Whether to center crop the image to the specified `crop_size`. Can be overridden by the `do_center_crop`
  68. parameter in the `preprocess` method.
  69. crop_size (`Dict[str, int]`, *optional*, defaults to `{"height": 224, "width": 224}`):
  70. Size of the image after applying the center crop. Can be overridden by the `crop_size` parameter in the
  71. `preprocess` method.
  72. do_rescale (`bool`, *optional*, defaults to `True`):
  73. Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
  74. parameter in the `preprocess` method.
  75. rescale_factor (`int` or `float`, *optional*, defaults to `1/127.5`):
  76. Defines the scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter
  77. in the `preprocess` method.
  78. offset (`bool`, *optional*, defaults to `True`):
  79. Whether to scale the image in both negative and positive directions. Can be overriden by the `offset` in
  80. the `preprocess` method.
  81. do_normalize (`bool`, *optional*, defaults to `True`):
  82. Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
  83. method.
  84. image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
  85. Mean to use if normalizing the image. This is a float or list of floats the length of the number of
  86. channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
  87. image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
  88. Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
  89. number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
  90. """
  91. model_input_names = ["pixel_values"]
  92. def __init__(
  93. self,
  94. do_resize: bool = True,
  95. size: Dict[str, int] = None,
  96. resample: PILImageResampling = PILImageResampling.BILINEAR,
  97. do_center_crop: bool = True,
  98. crop_size: Dict[str, int] = None,
  99. do_rescale: bool = True,
  100. rescale_factor: Union[int, float] = 1 / 127.5,
  101. offset: bool = True,
  102. do_normalize: bool = True,
  103. image_mean: Optional[Union[float, List[float]]] = None,
  104. image_std: Optional[Union[float, List[float]]] = None,
  105. **kwargs,
  106. ) -> None:
  107. super().__init__(**kwargs)
  108. size = size if size is not None else {"shortest_edge": 256}
  109. size = get_size_dict(size, default_to_square=False)
  110. crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
  111. crop_size = get_size_dict(crop_size, param_name="crop_size")
  112. self.do_resize = do_resize
  113. self.size = size
  114. self.do_center_crop = do_center_crop
  115. self.crop_size = crop_size
  116. self.resample = resample
  117. self.do_rescale = do_rescale
  118. self.rescale_factor = rescale_factor
  119. self.offset = offset
  120. self.do_normalize = do_normalize
  121. self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
  122. self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
  123. def resize(
  124. self,
  125. image: np.ndarray,
  126. size: Dict[str, int],
  127. resample: PILImageResampling = PILImageResampling.BILINEAR,
  128. data_format: Optional[Union[str, ChannelDimension]] = None,
  129. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  130. **kwargs,
  131. ) -> np.ndarray:
  132. """
  133. Resize an image.
  134. Args:
  135. image (`np.ndarray`):
  136. Image to resize.
  137. size (`Dict[str, int]`):
  138. Size of the output image. If `size` is of the form `{"height": h, "width": w}`, the output image will
  139. have the size `(h, w)`. If `size` is of the form `{"shortest_edge": s}`, the output image will have its
  140. shortest edge of length `s` while keeping the aspect ratio of the original image.
  141. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
  142. Resampling filter to use when resiizing the image.
  143. data_format (`str` or `ChannelDimension`, *optional*):
  144. The channel dimension format of the image. If not provided, it will be the same as the input image.
  145. input_data_format (`str` or `ChannelDimension`, *optional*):
  146. The channel dimension format of the input image. If not provided, it will be inferred.
  147. """
  148. size = get_size_dict(size, default_to_square=False)
  149. if "shortest_edge" in size:
  150. output_size = get_resize_output_image_size(
  151. image, size["shortest_edge"], default_to_square=False, input_data_format=input_data_format
  152. )
  153. elif "height" in size and "width" in size:
  154. output_size = (size["height"], size["width"])
  155. else:
  156. raise ValueError(f"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}")
  157. return resize(
  158. image,
  159. size=output_size,
  160. resample=resample,
  161. data_format=data_format,
  162. input_data_format=input_data_format,
  163. **kwargs,
  164. )
  165. # Copied from transformers.models.efficientnet.image_processing_efficientnet.EfficientNetImageProcessor.rescale
  166. def rescale(
  167. self,
  168. image: np.ndarray,
  169. scale: Union[int, float],
  170. offset: bool = True,
  171. data_format: Optional[Union[str, ChannelDimension]] = None,
  172. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  173. **kwargs,
  174. ):
  175. """
  176. Rescale an image by a scale factor.
  177. If `offset` is `True`, the image has its values rescaled by `scale` and then offset by 1. If `scale` is
  178. 1/127.5, the image is rescaled between [-1, 1].
  179. image = image * scale - 1
  180. If `offset` is `False`, and `scale` is 1/255, the image is rescaled between [0, 1].
  181. image = image * scale
  182. Args:
  183. image (`np.ndarray`):
  184. Image to rescale.
  185. scale (`int` or `float`):
  186. Scale to apply to the image.
  187. offset (`bool`, *optional*):
  188. Whether to scale the image in both negative and positive directions.
  189. data_format (`str` or `ChannelDimension`, *optional*):
  190. The channel dimension format of the image. If not provided, it will be the same as the input image.
  191. input_data_format (`ChannelDimension` or `str`, *optional*):
  192. The channel dimension format of the input image. If not provided, it will be inferred.
  193. """
  194. rescaled_image = rescale(
  195. image, scale=scale, data_format=data_format, input_data_format=input_data_format, **kwargs
  196. )
  197. if offset:
  198. rescaled_image = rescaled_image - 1
  199. return rescaled_image
  200. def _preprocess_image(
  201. self,
  202. image: ImageInput,
  203. do_resize: bool = None,
  204. size: Dict[str, int] = None,
  205. resample: PILImageResampling = None,
  206. do_center_crop: bool = None,
  207. crop_size: Dict[str, int] = None,
  208. do_rescale: bool = None,
  209. rescale_factor: float = None,
  210. offset: bool = None,
  211. do_normalize: bool = None,
  212. image_mean: Optional[Union[float, List[float]]] = None,
  213. image_std: Optional[Union[float, List[float]]] = None,
  214. data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
  215. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  216. ) -> np.ndarray:
  217. """Preprocesses a single image."""
  218. validate_preprocess_arguments(
  219. do_rescale=do_rescale,
  220. rescale_factor=rescale_factor,
  221. do_normalize=do_normalize,
  222. image_mean=image_mean,
  223. image_std=image_std,
  224. do_center_crop=do_center_crop,
  225. crop_size=crop_size,
  226. do_resize=do_resize,
  227. size=size,
  228. resample=resample,
  229. )
  230. if offset and not do_rescale:
  231. raise ValueError("For offset, do_rescale must also be set to True.")
  232. # All transformations expect numpy arrays.
  233. image = to_numpy_array(image)
  234. if is_scaled_image(image) and do_rescale:
  235. logger.warning_once(
  236. "It looks like you are trying to rescale already rescaled images. If the input"
  237. " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
  238. )
  239. if input_data_format is None:
  240. input_data_format = infer_channel_dimension_format(image)
  241. if do_resize:
  242. image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
  243. if do_center_crop:
  244. image = self.center_crop(image, size=crop_size, input_data_format=input_data_format)
  245. if do_rescale:
  246. image = self.rescale(image=image, scale=rescale_factor, offset=offset, input_data_format=input_data_format)
  247. if do_normalize:
  248. image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
  249. image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
  250. return image
  251. @filter_out_non_signature_kwargs()
  252. def preprocess(
  253. self,
  254. videos: ImageInput,
  255. do_resize: bool = None,
  256. size: Dict[str, int] = None,
  257. resample: PILImageResampling = None,
  258. do_center_crop: bool = None,
  259. crop_size: Dict[str, int] = None,
  260. do_rescale: bool = None,
  261. rescale_factor: float = None,
  262. offset: bool = None,
  263. do_normalize: bool = None,
  264. image_mean: Optional[Union[float, List[float]]] = None,
  265. image_std: Optional[Union[float, List[float]]] = None,
  266. return_tensors: Optional[Union[str, TensorType]] = None,
  267. data_format: ChannelDimension = ChannelDimension.FIRST,
  268. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  269. ) -> PIL.Image.Image:
  270. """
  271. Preprocess an image or batch of images.
  272. Args:
  273. videos (`ImageInput`):
  274. Video frames to preprocess. Expects a single or batch of video frames with pixel values ranging from 0
  275. to 255. If passing in frames with pixel values between 0 and 1, set `do_rescale=False`.
  276. do_resize (`bool`, *optional*, defaults to `self.do_resize`):
  277. Whether to resize the image.
  278. size (`Dict[str, int]`, *optional*, defaults to `self.size`):
  279. Size of the image after applying resize.
  280. resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
  281. Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only
  282. has an effect if `do_resize` is set to `True`.
  283. do_center_crop (`bool`, *optional*, defaults to `self.do_centre_crop`):
  284. Whether to centre crop the image.
  285. crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
  286. Size of the image after applying the centre crop.
  287. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
  288. Whether to rescale the image values between `[-1 - 1]` if `offset` is `True`, `[0, 1]` otherwise.
  289. rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
  290. Rescale factor to rescale the image by if `do_rescale` is set to `True`.
  291. offset (`bool`, *optional*, defaults to `self.offset`):
  292. Whether to scale the image in both negative and positive directions.
  293. do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
  294. Whether to normalize the image.
  295. image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
  296. Image mean.
  297. image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
  298. Image standard deviation.
  299. return_tensors (`str` or `TensorType`, *optional*):
  300. The type of tensors to return. Can be one of:
  301. - Unset: Return a list of `np.ndarray`.
  302. - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
  303. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
  304. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
  305. - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
  306. data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
  307. The channel dimension format for the output image. Can be one of:
  308. - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  309. - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  310. - Unset: Use the inferred channel dimension format of the input image.
  311. input_data_format (`ChannelDimension` or `str`, *optional*):
  312. The channel dimension format for the input image. If unset, the channel dimension format is inferred
  313. from the input image. Can be one of:
  314. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  315. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  316. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  317. """
  318. do_resize = do_resize if do_resize is not None else self.do_resize
  319. resample = resample if resample is not None else self.resample
  320. do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
  321. do_rescale = do_rescale if do_rescale is not None else self.do_rescale
  322. rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
  323. offset = offset if offset is not None else self.offset
  324. do_normalize = do_normalize if do_normalize is not None else self.do_normalize
  325. image_mean = image_mean if image_mean is not None else self.image_mean
  326. image_std = image_std if image_std is not None else self.image_std
  327. size = size if size is not None else self.size
  328. size = get_size_dict(size, default_to_square=False)
  329. crop_size = crop_size if crop_size is not None else self.crop_size
  330. crop_size = get_size_dict(crop_size, param_name="crop_size")
  331. if not valid_images(videos):
  332. raise ValueError(
  333. "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
  334. "torch.Tensor, tf.Tensor or jax.ndarray."
  335. )
  336. videos = make_batched(videos)
  337. videos = [
  338. [
  339. self._preprocess_image(
  340. image=img,
  341. do_resize=do_resize,
  342. size=size,
  343. resample=resample,
  344. do_center_crop=do_center_crop,
  345. crop_size=crop_size,
  346. do_rescale=do_rescale,
  347. rescale_factor=rescale_factor,
  348. offset=offset,
  349. do_normalize=do_normalize,
  350. image_mean=image_mean,
  351. image_std=image_std,
  352. data_format=data_format,
  353. input_data_format=input_data_format,
  354. )
  355. for img in video
  356. ]
  357. for video in videos
  358. ]
  359. data = {"pixel_values": videos}
  360. return BatchFeature(data=data, tensor_type=return_tensors)