image_processing_instructblipvideo.py 17 KB

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