image_processing_mobilevit.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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 MobileViT."""
  16. from typing import Dict, 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 flip_channel_order, get_resize_output_image_size, resize, to_channel_dimension_format
  20. from ...image_utils import (
  21. ChannelDimension,
  22. ImageInput,
  23. PILImageResampling,
  24. infer_channel_dimension_format,
  25. is_scaled_image,
  26. make_list_of_images,
  27. to_numpy_array,
  28. valid_images,
  29. validate_preprocess_arguments,
  30. )
  31. from ...utils import (
  32. TensorType,
  33. filter_out_non_signature_kwargs,
  34. is_torch_available,
  35. is_torch_tensor,
  36. is_vision_available,
  37. logging,
  38. )
  39. if is_vision_available():
  40. import PIL
  41. if is_torch_available():
  42. import torch
  43. logger = logging.get_logger(__name__)
  44. class MobileViTImageProcessor(BaseImageProcessor):
  45. r"""
  46. Constructs a MobileViT image processor.
  47. Args:
  48. do_resize (`bool`, *optional*, defaults to `True`):
  49. Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
  50. `do_resize` parameter in the `preprocess` method.
  51. size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
  52. Controls the size of the output image after resizing. Can be overridden by the `size` parameter in the
  53. `preprocess` method.
  54. resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
  55. Defines the resampling filter to use if resizing the image. Can be overridden by the `resample` parameter
  56. in the `preprocess` method.
  57. do_rescale (`bool`, *optional*, defaults to `True`):
  58. Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
  59. parameter in the `preprocess` method.
  60. rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
  61. Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
  62. `preprocess` method.
  63. do_center_crop (`bool`, *optional*, defaults to `True`):
  64. Whether to crop the input at the center. If the input size is smaller than `crop_size` along any edge, the
  65. image is padded with 0's and then center cropped. Can be overridden by the `do_center_crop` parameter in
  66. the `preprocess` method.
  67. crop_size (`Dict[str, int]`, *optional*, defaults to `{"height": 256, "width": 256}`):
  68. Desired output size `(size["height"], size["width"])` when applying center-cropping. Can be overridden by
  69. the `crop_size` parameter in the `preprocess` method.
  70. do_flip_channel_order (`bool`, *optional*, defaults to `True`):
  71. Whether to flip the color channels from RGB to BGR. Can be overridden by the `do_flip_channel_order`
  72. parameter in the `preprocess` method.
  73. """
  74. model_input_names = ["pixel_values"]
  75. def __init__(
  76. self,
  77. do_resize: bool = True,
  78. size: Dict[str, int] = None,
  79. resample: PILImageResampling = PILImageResampling.BILINEAR,
  80. do_rescale: bool = True,
  81. rescale_factor: Union[int, float] = 1 / 255,
  82. do_center_crop: bool = True,
  83. crop_size: Dict[str, int] = None,
  84. do_flip_channel_order: bool = True,
  85. **kwargs,
  86. ) -> None:
  87. super().__init__(**kwargs)
  88. size = size if size is not None else {"shortest_edge": 224}
  89. size = get_size_dict(size, default_to_square=False)
  90. crop_size = crop_size if crop_size is not None else {"height": 256, "width": 256}
  91. crop_size = get_size_dict(crop_size, param_name="crop_size")
  92. self.do_resize = do_resize
  93. self.size = size
  94. self.resample = resample
  95. self.do_rescale = do_rescale
  96. self.rescale_factor = rescale_factor
  97. self.do_center_crop = do_center_crop
  98. self.crop_size = crop_size
  99. self.do_flip_channel_order = do_flip_channel_order
  100. # Copied from transformers.models.mobilenet_v1.image_processing_mobilenet_v1.MobileNetV1ImageProcessor.resize with PILImageResampling.BICUBIC->PILImageResampling.BILINEAR
  101. def resize(
  102. self,
  103. image: np.ndarray,
  104. size: Dict[str, int],
  105. resample: PILImageResampling = PILImageResampling.BILINEAR,
  106. data_format: Optional[Union[str, ChannelDimension]] = None,
  107. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  108. **kwargs,
  109. ) -> np.ndarray:
  110. """
  111. Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge
  112. resized to keep the input aspect ratio.
  113. Args:
  114. image (`np.ndarray`):
  115. Image to resize.
  116. size (`Dict[str, int]`):
  117. Size of the output image.
  118. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
  119. Resampling filter to use when resiizing the image.
  120. data_format (`str` or `ChannelDimension`, *optional*):
  121. The channel dimension format of the image. If not provided, it will be the same as the input image.
  122. input_data_format (`ChannelDimension` or `str`, *optional*):
  123. The channel dimension format of the input image. If not provided, it will be inferred.
  124. """
  125. default_to_square = True
  126. if "shortest_edge" in size:
  127. size = size["shortest_edge"]
  128. default_to_square = False
  129. elif "height" in size and "width" in size:
  130. size = (size["height"], size["width"])
  131. else:
  132. raise ValueError("Size must contain either 'shortest_edge' or 'height' and 'width'.")
  133. output_size = get_resize_output_image_size(
  134. image,
  135. size=size,
  136. default_to_square=default_to_square,
  137. input_data_format=input_data_format,
  138. )
  139. return resize(
  140. image,
  141. size=output_size,
  142. resample=resample,
  143. data_format=data_format,
  144. input_data_format=input_data_format,
  145. **kwargs,
  146. )
  147. def flip_channel_order(
  148. self,
  149. image: np.ndarray,
  150. data_format: Optional[Union[str, ChannelDimension]] = None,
  151. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  152. ) -> np.ndarray:
  153. """
  154. Flip the color channels from RGB to BGR or vice versa.
  155. Args:
  156. image (`np.ndarray`):
  157. The image, represented as a numpy array.
  158. data_format (`ChannelDimension` or `str`, *optional*):
  159. The channel dimension format of the image. If not provided, it will be the same as the input image.
  160. input_data_format (`ChannelDimension` or `str`, *optional*):
  161. The channel dimension format of the input image. If not provided, it will be inferred.
  162. """
  163. return flip_channel_order(image, data_format=data_format, input_data_format=input_data_format)
  164. def __call__(self, images, segmentation_maps=None, **kwargs):
  165. """
  166. Preprocesses a batch of images and optionally segmentation maps.
  167. Overrides the `__call__` method of the `Preprocessor` class so that both images and segmentation maps can be
  168. passed in as positional arguments.
  169. """
  170. return super().__call__(images, segmentation_maps=segmentation_maps, **kwargs)
  171. def _preprocess(
  172. self,
  173. image: ImageInput,
  174. do_resize: bool,
  175. do_rescale: bool,
  176. do_center_crop: bool,
  177. do_flip_channel_order: bool,
  178. size: Optional[Dict[str, int]] = None,
  179. resample: PILImageResampling = None,
  180. rescale_factor: Optional[float] = None,
  181. crop_size: Optional[Dict[str, int]] = None,
  182. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  183. ):
  184. if do_resize:
  185. image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
  186. if do_rescale:
  187. image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
  188. if do_center_crop:
  189. image = self.center_crop(image=image, size=crop_size, input_data_format=input_data_format)
  190. if do_flip_channel_order:
  191. image = self.flip_channel_order(image, input_data_format=input_data_format)
  192. return image
  193. def _preprocess_image(
  194. self,
  195. image: ImageInput,
  196. do_resize: bool = None,
  197. size: Dict[str, int] = None,
  198. resample: PILImageResampling = None,
  199. do_rescale: bool = None,
  200. rescale_factor: float = None,
  201. do_center_crop: bool = None,
  202. crop_size: Dict[str, int] = None,
  203. do_flip_channel_order: bool = None,
  204. data_format: Optional[Union[str, ChannelDimension]] = None,
  205. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  206. ) -> np.ndarray:
  207. """Preprocesses a single image."""
  208. # All transformations expect numpy arrays.
  209. image = to_numpy_array(image)
  210. if is_scaled_image(image) and do_rescale:
  211. logger.warning_once(
  212. "It looks like you are trying to rescale already rescaled images. If the input"
  213. " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
  214. )
  215. if input_data_format is None:
  216. input_data_format = infer_channel_dimension_format(image)
  217. image = self._preprocess(
  218. image=image,
  219. do_resize=do_resize,
  220. size=size,
  221. resample=resample,
  222. do_rescale=do_rescale,
  223. rescale_factor=rescale_factor,
  224. do_center_crop=do_center_crop,
  225. crop_size=crop_size,
  226. do_flip_channel_order=do_flip_channel_order,
  227. input_data_format=input_data_format,
  228. )
  229. image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
  230. return image
  231. def _preprocess_mask(
  232. self,
  233. segmentation_map: ImageInput,
  234. do_resize: bool = None,
  235. size: Dict[str, int] = None,
  236. do_center_crop: bool = None,
  237. crop_size: Dict[str, int] = None,
  238. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  239. ) -> np.ndarray:
  240. """Preprocesses a single mask."""
  241. segmentation_map = to_numpy_array(segmentation_map)
  242. # Add channel dimension if missing - needed for certain transformations
  243. if segmentation_map.ndim == 2:
  244. added_channel_dim = True
  245. segmentation_map = segmentation_map[None, ...]
  246. input_data_format = ChannelDimension.FIRST
  247. else:
  248. added_channel_dim = False
  249. if input_data_format is None:
  250. input_data_format = infer_channel_dimension_format(segmentation_map, num_channels=1)
  251. segmentation_map = self._preprocess(
  252. image=segmentation_map,
  253. do_resize=do_resize,
  254. size=size,
  255. resample=PILImageResampling.NEAREST,
  256. do_rescale=False,
  257. do_center_crop=do_center_crop,
  258. crop_size=crop_size,
  259. do_flip_channel_order=False,
  260. input_data_format=input_data_format,
  261. )
  262. # Remove extra channel dimension if added for processing
  263. if added_channel_dim:
  264. segmentation_map = segmentation_map.squeeze(0)
  265. segmentation_map = segmentation_map.astype(np.int64)
  266. return segmentation_map
  267. @filter_out_non_signature_kwargs()
  268. def preprocess(
  269. self,
  270. images: ImageInput,
  271. segmentation_maps: Optional[ImageInput] = None,
  272. do_resize: bool = None,
  273. size: Dict[str, int] = None,
  274. resample: PILImageResampling = None,
  275. do_rescale: bool = None,
  276. rescale_factor: float = None,
  277. do_center_crop: bool = None,
  278. crop_size: Dict[str, int] = None,
  279. do_flip_channel_order: bool = None,
  280. return_tensors: Optional[Union[str, TensorType]] = None,
  281. data_format: ChannelDimension = ChannelDimension.FIRST,
  282. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  283. ) -> PIL.Image.Image:
  284. """
  285. Preprocess an image or batch of images.
  286. Args:
  287. images (`ImageInput`):
  288. Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
  289. passing in images with pixel values between 0 and 1, set `do_rescale=False`.
  290. segmentation_maps (`ImageInput`, *optional*):
  291. Segmentation map to preprocess.
  292. do_resize (`bool`, *optional*, defaults to `self.do_resize`):
  293. Whether to resize the image.
  294. size (`Dict[str, int]`, *optional*, defaults to `self.size`):
  295. Size of the image after resizing.
  296. resample (`int`, *optional*, defaults to `self.resample`):
  297. Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only
  298. has an effect if `do_resize` is set to `True`.
  299. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
  300. Whether to rescale the image by rescale factor.
  301. rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
  302. Rescale factor to rescale the image by if `do_rescale` is set to `True`.
  303. do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
  304. Whether to center crop the image.
  305. crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
  306. Size of the center crop if `do_center_crop` is set to `True`.
  307. do_flip_channel_order (`bool`, *optional*, defaults to `self.do_flip_channel_order`):
  308. Whether to flip the channel order of the image.
  309. return_tensors (`str` or `TensorType`, *optional*):
  310. The type of tensors to return. Can be one of:
  311. - Unset: Return a list of `np.ndarray`.
  312. - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
  313. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
  314. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
  315. - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
  316. data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
  317. The channel dimension format for the output image. Can be one of:
  318. - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  319. - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  320. input_data_format (`ChannelDimension` or `str`, *optional*):
  321. The channel dimension format for the input image. If unset, the channel dimension format is inferred
  322. from the input image. Can be one of:
  323. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  324. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  325. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  326. """
  327. do_resize = do_resize if do_resize is not None else self.do_resize
  328. resample = resample if resample is not None else self.resample
  329. do_rescale = do_rescale if do_rescale is not None else self.do_rescale
  330. rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
  331. do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
  332. do_flip_channel_order = (
  333. do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order
  334. )
  335. size = size if size is not None else self.size
  336. size = get_size_dict(size, default_to_square=False)
  337. crop_size = crop_size if crop_size is not None else self.crop_size
  338. crop_size = get_size_dict(crop_size, param_name="crop_size")
  339. images = make_list_of_images(images)
  340. if segmentation_maps is not None:
  341. segmentation_maps = make_list_of_images(segmentation_maps, expected_ndims=2)
  342. images = make_list_of_images(images)
  343. if not valid_images(images):
  344. raise ValueError(
  345. "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
  346. "torch.Tensor, tf.Tensor or jax.ndarray."
  347. )
  348. if segmentation_maps is not None and not valid_images(segmentation_maps):
  349. raise ValueError(
  350. "Invalid segmentation map type. Must be of type PIL.Image.Image, numpy.ndarray, "
  351. "torch.Tensor, tf.Tensor or jax.ndarray."
  352. )
  353. validate_preprocess_arguments(
  354. do_rescale=do_rescale,
  355. rescale_factor=rescale_factor,
  356. do_center_crop=do_center_crop,
  357. crop_size=crop_size,
  358. do_resize=do_resize,
  359. size=size,
  360. resample=resample,
  361. )
  362. images = [
  363. self._preprocess_image(
  364. image=img,
  365. do_resize=do_resize,
  366. size=size,
  367. resample=resample,
  368. do_rescale=do_rescale,
  369. rescale_factor=rescale_factor,
  370. do_center_crop=do_center_crop,
  371. crop_size=crop_size,
  372. do_flip_channel_order=do_flip_channel_order,
  373. data_format=data_format,
  374. input_data_format=input_data_format,
  375. )
  376. for img in images
  377. ]
  378. data = {"pixel_values": images}
  379. if segmentation_maps is not None:
  380. segmentation_maps = [
  381. self._preprocess_mask(
  382. segmentation_map=segmentation_map,
  383. do_resize=do_resize,
  384. size=size,
  385. do_center_crop=do_center_crop,
  386. crop_size=crop_size,
  387. input_data_format=input_data_format,
  388. )
  389. for segmentation_map in segmentation_maps
  390. ]
  391. data["labels"] = segmentation_maps
  392. return BatchFeature(data=data, tensor_type=return_tensors)
  393. # Copied from transformers.models.beit.image_processing_beit.BeitImageProcessor.post_process_semantic_segmentation with Beit->MobileViT
  394. def post_process_semantic_segmentation(self, outputs, target_sizes: List[Tuple] = None):
  395. """
  396. Converts the output of [`MobileViTForSemanticSegmentation`] into semantic segmentation maps. Only supports PyTorch.
  397. Args:
  398. outputs ([`MobileViTForSemanticSegmentation`]):
  399. Raw outputs of the model.
  400. target_sizes (`List[Tuple]` of length `batch_size`, *optional*):
  401. List of tuples corresponding to the requested final size (height, width) of each prediction. If unset,
  402. predictions will not be resized.
  403. Returns:
  404. semantic_segmentation: `List[torch.Tensor]` of length `batch_size`, where each item is a semantic
  405. segmentation map of shape (height, width) corresponding to the target_sizes entry (if `target_sizes` is
  406. specified). Each entry of each `torch.Tensor` correspond to a semantic class id.
  407. """
  408. # TODO: add support for other frameworks
  409. logits = outputs.logits
  410. # Resize logits and compute semantic segmentation maps
  411. if target_sizes is not None:
  412. if len(logits) != len(target_sizes):
  413. raise ValueError(
  414. "Make sure that you pass in as many target sizes as the batch dimension of the logits"
  415. )
  416. if is_torch_tensor(target_sizes):
  417. target_sizes = target_sizes.numpy()
  418. semantic_segmentation = []
  419. for idx in range(len(logits)):
  420. resized_logits = torch.nn.functional.interpolate(
  421. logits[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False
  422. )
  423. semantic_map = resized_logits[0].argmax(dim=0)
  424. semantic_segmentation.append(semantic_map)
  425. else:
  426. semantic_segmentation = logits.argmax(dim=1)
  427. semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
  428. return semantic_segmentation