image_processing_beit.py 24 KB

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