image_processing_videomae.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. # coding=utf-8
  2. # Copyright 2022 The 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 VideoMAE."""
  16. from typing import Dict, List, Optional, Union
  17. import numpy as np
  18. from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
  19. from ...image_transforms import (
  20. get_resize_output_image_size,
  21. resize,
  22. to_channel_dimension_format,
  23. )
  24. from ...image_utils import (
  25. IMAGENET_STANDARD_MEAN,
  26. IMAGENET_STANDARD_STD,
  27. ChannelDimension,
  28. ImageInput,
  29. PILImageResampling,
  30. infer_channel_dimension_format,
  31. is_scaled_image,
  32. is_valid_image,
  33. to_numpy_array,
  34. valid_images,
  35. validate_preprocess_arguments,
  36. )
  37. from ...utils import TensorType, filter_out_non_signature_kwargs, is_vision_available, logging
  38. if is_vision_available():
  39. import PIL
  40. logger = logging.get_logger(__name__)
  41. def make_batched(videos) -> List[List[ImageInput]]:
  42. if isinstance(videos, (list, tuple)) and isinstance(videos[0], (list, tuple)) and is_valid_image(videos[0][0]):
  43. return videos
  44. elif isinstance(videos, (list, tuple)) and is_valid_image(videos[0]):
  45. return [videos]
  46. elif is_valid_image(videos):
  47. return [[videos]]
  48. raise ValueError(f"Could not make batched video from {videos}")
  49. class VideoMAEImageProcessor(BaseImageProcessor):
  50. r"""
  51. Constructs a VideoMAE image processor.
  52. Args:
  53. do_resize (`bool`, *optional*, defaults to `True`):
  54. Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
  55. `do_resize` parameter in the `preprocess` method.
  56. size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
  57. Size of the output image after resizing. The shortest edge of the image will be resized to
  58. `size["shortest_edge"]` while maintaining the aspect ratio of the original image. Can be overriden by
  59. `size` in the `preprocess` method.
  60. resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
  61. Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
  62. `preprocess` method.
  63. do_center_crop (`bool`, *optional*, defaults to `True`):
  64. Whether to center crop the image to the specified `crop_size`. Can be overridden by the `do_center_crop`
  65. parameter in the `preprocess` method.
  66. crop_size (`Dict[str, int]`, *optional*, defaults to `{"height": 224, "width": 224}`):
  67. Size of the image after applying the center crop. Can be overridden by the `crop_size` parameter in the
  68. `preprocess` method.
  69. do_rescale (`bool`, *optional*, defaults to `True`):
  70. Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
  71. parameter in the `preprocess` method.
  72. rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
  73. Defines the scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter
  74. in the `preprocess` method.
  75. do_normalize (`bool`, *optional*, defaults to `True`):
  76. Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
  77. method.
  78. image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
  79. Mean to use if normalizing the image. This is a float or list of floats the length of the number of
  80. channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
  81. image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
  82. Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
  83. number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
  84. """
  85. model_input_names = ["pixel_values"]
  86. def __init__(
  87. self,
  88. do_resize: bool = True,
  89. size: Dict[str, int] = None,
  90. resample: PILImageResampling = PILImageResampling.BILINEAR,
  91. do_center_crop: bool = True,
  92. crop_size: Dict[str, int] = None,
  93. do_rescale: bool = True,
  94. rescale_factor: Union[int, float] = 1 / 255,
  95. do_normalize: bool = True,
  96. image_mean: Optional[Union[float, List[float]]] = None,
  97. image_std: Optional[Union[float, List[float]]] = None,
  98. **kwargs,
  99. ) -> None:
  100. super().__init__(**kwargs)
  101. size = size if size is not None else {"shortest_edge": 224}
  102. size = get_size_dict(size, default_to_square=False)
  103. crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
  104. crop_size = get_size_dict(crop_size, param_name="crop_size")
  105. self.do_resize = do_resize
  106. self.size = size
  107. self.do_center_crop = do_center_crop
  108. self.crop_size = crop_size
  109. self.resample = resample
  110. self.do_rescale = do_rescale
  111. self.rescale_factor = rescale_factor
  112. self.do_normalize = do_normalize
  113. self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
  114. self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
  115. def resize(
  116. self,
  117. image: np.ndarray,
  118. size: Dict[str, int],
  119. resample: PILImageResampling = PILImageResampling.BILINEAR,
  120. data_format: Optional[Union[str, ChannelDimension]] = None,
  121. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  122. **kwargs,
  123. ) -> np.ndarray:
  124. """
  125. Resize an image.
  126. Args:
  127. image (`np.ndarray`):
  128. Image to resize.
  129. size (`Dict[str, int]`):
  130. Size of the output image. If `size` is of the form `{"height": h, "width": w}`, the output image will
  131. have the size `(h, w)`. If `size` is of the form `{"shortest_edge": s}`, the output image will have its
  132. shortest edge of length `s` while keeping the aspect ratio of the original image.
  133. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
  134. Resampling filter to use when resiizing the image.
  135. data_format (`str` or `ChannelDimension`, *optional*):
  136. The channel dimension format of the image. If not provided, it will be the same as the input image.
  137. input_data_format (`str` or `ChannelDimension`, *optional*):
  138. The channel dimension format of the input image. If not provided, it will be inferred.
  139. """
  140. size = get_size_dict(size, default_to_square=False)
  141. if "shortest_edge" in size:
  142. output_size = get_resize_output_image_size(
  143. image, size["shortest_edge"], default_to_square=False, input_data_format=input_data_format
  144. )
  145. elif "height" in size and "width" in size:
  146. output_size = (size["height"], size["width"])
  147. else:
  148. raise ValueError(f"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}")
  149. return resize(
  150. image,
  151. size=output_size,
  152. resample=resample,
  153. data_format=data_format,
  154. input_data_format=input_data_format,
  155. **kwargs,
  156. )
  157. def _preprocess_image(
  158. self,
  159. image: ImageInput,
  160. do_resize: bool = None,
  161. size: Dict[str, int] = None,
  162. resample: PILImageResampling = None,
  163. do_center_crop: bool = None,
  164. crop_size: Dict[str, int] = None,
  165. do_rescale: bool = None,
  166. rescale_factor: float = None,
  167. do_normalize: bool = None,
  168. image_mean: Optional[Union[float, List[float]]] = None,
  169. image_std: Optional[Union[float, List[float]]] = None,
  170. data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
  171. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  172. ) -> np.ndarray:
  173. """Preprocesses a single image."""
  174. validate_preprocess_arguments(
  175. do_rescale=do_rescale,
  176. rescale_factor=rescale_factor,
  177. do_normalize=do_normalize,
  178. image_mean=image_mean,
  179. image_std=image_std,
  180. do_center_crop=do_center_crop,
  181. crop_size=crop_size,
  182. do_resize=do_resize,
  183. size=size,
  184. resample=resample,
  185. )
  186. # All transformations expect numpy arrays.
  187. image = to_numpy_array(image)
  188. if is_scaled_image(image) and do_rescale:
  189. logger.warning_once(
  190. "It looks like you are trying to rescale already rescaled images. If the input"
  191. " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
  192. )
  193. if input_data_format is None:
  194. input_data_format = infer_channel_dimension_format(image)
  195. if do_resize:
  196. image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
  197. if do_center_crop:
  198. image = self.center_crop(image, size=crop_size, input_data_format=input_data_format)
  199. if do_rescale:
  200. image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
  201. if do_normalize:
  202. image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
  203. image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
  204. return image
  205. @filter_out_non_signature_kwargs()
  206. def preprocess(
  207. self,
  208. videos: ImageInput,
  209. do_resize: bool = None,
  210. size: Dict[str, int] = None,
  211. resample: PILImageResampling = None,
  212. do_center_crop: bool = None,
  213. crop_size: Dict[str, int] = None,
  214. do_rescale: bool = None,
  215. rescale_factor: float = None,
  216. do_normalize: bool = None,
  217. image_mean: Optional[Union[float, List[float]]] = None,
  218. image_std: Optional[Union[float, List[float]]] = None,
  219. return_tensors: Optional[Union[str, TensorType]] = None,
  220. data_format: ChannelDimension = ChannelDimension.FIRST,
  221. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  222. ) -> PIL.Image.Image:
  223. """
  224. Preprocess an image or batch of images.
  225. Args:
  226. images (`ImageInput`):
  227. Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
  228. passing in images with pixel values between 0 and 1, set `do_rescale=False`.
  229. do_resize (`bool`, *optional*, defaults to `self.do_resize`):
  230. Whether to resize the image.
  231. size (`Dict[str, int]`, *optional*, defaults to `self.size`):
  232. Size of the image after applying resize.
  233. resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
  234. Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only
  235. has an effect if `do_resize` is set to `True`.
  236. do_center_crop (`bool`, *optional*, defaults to `self.do_centre_crop`):
  237. Whether to centre crop the image.
  238. crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
  239. Size of the image after applying the centre crop.
  240. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
  241. Whether to rescale the image values between [0 - 1].
  242. rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
  243. Rescale factor to rescale the image by if `do_rescale` is set to `True`.
  244. do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
  245. Whether to normalize the image.
  246. image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
  247. Image mean.
  248. image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
  249. Image standard deviation.
  250. return_tensors (`str` or `TensorType`, *optional*):
  251. The type of tensors to return. Can be one of:
  252. - Unset: Return a list of `np.ndarray`.
  253. - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
  254. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
  255. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
  256. - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
  257. data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
  258. The channel dimension format for the output image. Can be one of:
  259. - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  260. - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  261. - Unset: Use the inferred channel dimension format of the input image.
  262. input_data_format (`ChannelDimension` or `str`, *optional*):
  263. The channel dimension format for the input image. If unset, the channel dimension format is inferred
  264. from the input image. Can be one of:
  265. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  266. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  267. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  268. """
  269. do_resize = do_resize if do_resize is not None else self.do_resize
  270. resample = resample if resample is not None else self.resample
  271. do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
  272. do_rescale = do_rescale if do_rescale is not None else self.do_rescale
  273. rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
  274. do_normalize = do_normalize if do_normalize is not None else self.do_normalize
  275. image_mean = image_mean if image_mean is not None else self.image_mean
  276. image_std = image_std if image_std is not None else self.image_std
  277. size = size if size is not None else self.size
  278. size = get_size_dict(size, default_to_square=False)
  279. crop_size = crop_size if crop_size is not None else self.crop_size
  280. crop_size = get_size_dict(crop_size, param_name="crop_size")
  281. if not valid_images(videos):
  282. raise ValueError(
  283. "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
  284. "torch.Tensor, tf.Tensor or jax.ndarray."
  285. )
  286. videos = make_batched(videos)
  287. videos = [
  288. [
  289. self._preprocess_image(
  290. image=img,
  291. do_resize=do_resize,
  292. size=size,
  293. resample=resample,
  294. do_center_crop=do_center_crop,
  295. crop_size=crop_size,
  296. do_rescale=do_rescale,
  297. rescale_factor=rescale_factor,
  298. do_normalize=do_normalize,
  299. image_mean=image_mean,
  300. image_std=image_std,
  301. data_format=data_format,
  302. input_data_format=input_data_format,
  303. )
  304. for img in video
  305. ]
  306. for video in videos
  307. ]
  308. data = {"pixel_values": videos}
  309. return BatchFeature(data=data, tensor_type=return_tensors)