image_processing_layoutlmv3.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 LayoutLMv3."""
  16. from typing import Dict, Iterable, Optional, Union
  17. import numpy as np
  18. from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
  19. from ...image_transforms import resize, to_channel_dimension_format, to_pil_image
  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_pytesseract_available,
  37. is_vision_available,
  38. logging,
  39. requires_backends,
  40. )
  41. if is_vision_available():
  42. import PIL
  43. # soft dependency
  44. if is_pytesseract_available():
  45. import pytesseract
  46. logger = logging.get_logger(__name__)
  47. def normalize_box(box, width, height):
  48. return [
  49. int(1000 * (box[0] / width)),
  50. int(1000 * (box[1] / height)),
  51. int(1000 * (box[2] / width)),
  52. int(1000 * (box[3] / height)),
  53. ]
  54. def apply_tesseract(
  55. image: np.ndarray,
  56. lang: Optional[str],
  57. tesseract_config: Optional[str],
  58. input_data_format: Optional[Union[ChannelDimension, str]] = None,
  59. ):
  60. """Applies Tesseract OCR on a document image, and returns recognized words + normalized bounding boxes."""
  61. # apply OCR
  62. pil_image = to_pil_image(image, input_data_format=input_data_format)
  63. image_width, image_height = pil_image.size
  64. data = pytesseract.image_to_data(pil_image, lang=lang, output_type="dict", config=tesseract_config)
  65. words, left, top, width, height = data["text"], data["left"], data["top"], data["width"], data["height"]
  66. # filter empty words and corresponding coordinates
  67. irrelevant_indices = [idx for idx, word in enumerate(words) if not word.strip()]
  68. words = [word for idx, word in enumerate(words) if idx not in irrelevant_indices]
  69. left = [coord for idx, coord in enumerate(left) if idx not in irrelevant_indices]
  70. top = [coord for idx, coord in enumerate(top) if idx not in irrelevant_indices]
  71. width = [coord for idx, coord in enumerate(width) if idx not in irrelevant_indices]
  72. height = [coord for idx, coord in enumerate(height) if idx not in irrelevant_indices]
  73. # turn coordinates into (left, top, left+width, top+height) format
  74. actual_boxes = []
  75. for x, y, w, h in zip(left, top, width, height):
  76. actual_box = [x, y, x + w, y + h]
  77. actual_boxes.append(actual_box)
  78. # finally, normalize the bounding boxes
  79. normalized_boxes = []
  80. for box in actual_boxes:
  81. normalized_boxes.append(normalize_box(box, image_width, image_height))
  82. assert len(words) == len(normalized_boxes), "Not as many words as there are bounding boxes"
  83. return words, normalized_boxes
  84. class LayoutLMv3ImageProcessor(BaseImageProcessor):
  85. r"""
  86. Constructs a LayoutLMv3 image processor.
  87. Args:
  88. do_resize (`bool`, *optional*, defaults to `True`):
  89. Whether to resize the image's (height, width) dimensions to `(size["height"], size["width"])`. Can be
  90. overridden by `do_resize` in `preprocess`.
  91. size (`Dict[str, int]` *optional*, defaults to `{"height": 224, "width": 224}`):
  92. Size of the image after resizing. Can be overridden by `size` in `preprocess`.
  93. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
  94. Resampling filter to use if resizing the image. Can be overridden by `resample` in `preprocess`.
  95. do_rescale (`bool`, *optional*, defaults to `True`):
  96. Whether to rescale the image's pixel values by the specified `rescale_value`. Can be overridden by
  97. `do_rescale` in `preprocess`.
  98. rescale_factor (`float`, *optional*, defaults to 1 / 255):
  99. Value by which the image's pixel values are rescaled. Can be overridden by `rescale_factor` in
  100. `preprocess`.
  101. do_normalize (`bool`, *optional*, defaults to `True`):
  102. Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
  103. method.
  104. image_mean (`Iterable[float]` or `float`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
  105. Mean to use if normalizing the image. This is a float or list of floats the length of the number of
  106. channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
  107. image_std (`Iterable[float]` or `float`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
  108. Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
  109. number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
  110. apply_ocr (`bool`, *optional*, defaults to `True`):
  111. Whether to apply the Tesseract OCR engine to get words + normalized bounding boxes. Can be overridden by
  112. the `apply_ocr` parameter in the `preprocess` method.
  113. ocr_lang (`str`, *optional*):
  114. The language, specified by its ISO code, to be used by the Tesseract OCR engine. By default, English is
  115. used. Can be overridden by the `ocr_lang` parameter in the `preprocess` method.
  116. tesseract_config (`str`, *optional*):
  117. Any additional custom configuration flags that are forwarded to the `config` parameter when calling
  118. Tesseract. For example: '--psm 6'. Can be overridden by the `tesseract_config` parameter in the
  119. `preprocess` method.
  120. """
  121. model_input_names = ["pixel_values"]
  122. def __init__(
  123. self,
  124. do_resize: bool = True,
  125. size: Dict[str, int] = None,
  126. resample: PILImageResampling = PILImageResampling.BILINEAR,
  127. do_rescale: bool = True,
  128. rescale_value: float = 1 / 255,
  129. do_normalize: bool = True,
  130. image_mean: Union[float, Iterable[float]] = None,
  131. image_std: Union[float, Iterable[float]] = None,
  132. apply_ocr: bool = True,
  133. ocr_lang: Optional[str] = None,
  134. tesseract_config: Optional[str] = "",
  135. **kwargs,
  136. ) -> None:
  137. super().__init__(**kwargs)
  138. size = size if size is not None else {"height": 224, "width": 224}
  139. size = get_size_dict(size)
  140. self.do_resize = do_resize
  141. self.size = size
  142. self.resample = resample
  143. self.do_rescale = do_rescale
  144. self.rescale_factor = rescale_value
  145. self.do_normalize = do_normalize
  146. self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
  147. self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
  148. self.apply_ocr = apply_ocr
  149. self.ocr_lang = ocr_lang
  150. self.tesseract_config = tesseract_config
  151. # Copied from transformers.models.vit.image_processing_vit.ViTImageProcessor.resize
  152. def resize(
  153. self,
  154. image: np.ndarray,
  155. size: Dict[str, int],
  156. resample: PILImageResampling = PILImageResampling.BILINEAR,
  157. data_format: Optional[Union[str, ChannelDimension]] = None,
  158. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  159. **kwargs,
  160. ) -> np.ndarray:
  161. """
  162. Resize an image to `(size["height"], size["width"])`.
  163. Args:
  164. image (`np.ndarray`):
  165. Image to resize.
  166. size (`Dict[str, int]`):
  167. Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
  168. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
  169. `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
  170. data_format (`ChannelDimension` or `str`, *optional*):
  171. The channel dimension format for the output image. If unset, the channel dimension format of the input
  172. image is used. Can be one of:
  173. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  174. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  175. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  176. input_data_format (`ChannelDimension` or `str`, *optional*):
  177. The channel dimension format for the input image. If unset, the channel dimension format is inferred
  178. from the input image. Can be one of:
  179. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  180. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  181. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  182. Returns:
  183. `np.ndarray`: The resized image.
  184. """
  185. size = get_size_dict(size)
  186. if "height" not in size or "width" not in size:
  187. raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
  188. output_size = (size["height"], size["width"])
  189. return resize(
  190. image,
  191. size=output_size,
  192. resample=resample,
  193. data_format=data_format,
  194. input_data_format=input_data_format,
  195. **kwargs,
  196. )
  197. @filter_out_non_signature_kwargs()
  198. def preprocess(
  199. self,
  200. images: ImageInput,
  201. do_resize: bool = None,
  202. size: Dict[str, int] = None,
  203. resample=None,
  204. do_rescale: bool = None,
  205. rescale_factor: float = None,
  206. do_normalize: bool = None,
  207. image_mean: Union[float, Iterable[float]] = None,
  208. image_std: Union[float, Iterable[float]] = None,
  209. apply_ocr: bool = None,
  210. ocr_lang: Optional[str] = None,
  211. tesseract_config: Optional[str] = None,
  212. return_tensors: Optional[Union[str, TensorType]] = None,
  213. data_format: ChannelDimension = ChannelDimension.FIRST,
  214. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  215. ) -> PIL.Image.Image:
  216. """
  217. Preprocess an image or batch of images.
  218. Args:
  219. images (`ImageInput`):
  220. Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
  221. passing in images with pixel values between 0 and 1, set `do_rescale=False`.
  222. do_resize (`bool`, *optional*, defaults to `self.do_resize`):
  223. Whether to resize the image.
  224. size (`Dict[str, int]`, *optional*, defaults to `self.size`):
  225. Desired size of the output image after applying `resize`.
  226. resample (`int`, *optional*, defaults to `self.resample`):
  227. Resampling filter to use if resizing the image. This can be one of the `PILImageResampling` filters.
  228. Only has an effect if `do_resize` is set to `True`.
  229. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
  230. Whether to rescale the image pixel values between [0, 1].
  231. rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
  232. Rescale factor to apply to the image pixel values. Only has an effect if `do_rescale` is set to `True`.
  233. do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
  234. Whether to normalize the image.
  235. image_mean (`float` or `Iterable[float]`, *optional*, defaults to `self.image_mean`):
  236. Mean values to be used for normalization. Only has an effect if `do_normalize` is set to `True`.
  237. image_std (`float` or `Iterable[float]`, *optional*, defaults to `self.image_std`):
  238. Standard deviation values to be used for normalization. Only has an effect if `do_normalize` is set to
  239. `True`.
  240. apply_ocr (`bool`, *optional*, defaults to `self.apply_ocr`):
  241. Whether to apply the Tesseract OCR engine to get words + normalized bounding boxes.
  242. ocr_lang (`str`, *optional*, defaults to `self.ocr_lang`):
  243. The language, specified by its ISO code, to be used by the Tesseract OCR engine. By default, English is
  244. used.
  245. tesseract_config (`str`, *optional*, defaults to `self.tesseract_config`):
  246. Any additional custom configuration flags that are forwarded to the `config` parameter when calling
  247. Tesseract.
  248. return_tensors (`str` or `TensorType`, *optional*):
  249. The type of tensors to return. Can be one of:
  250. - Unset: Return a list of `np.ndarray`.
  251. - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
  252. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
  253. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
  254. - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
  255. data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
  256. The channel dimension format for the output image. Can be one of:
  257. - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  258. - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  259. input_data_format (`ChannelDimension` or `str`, *optional*):
  260. The channel dimension format for the input image. If unset, the channel dimension format is inferred
  261. from the input image. Can be one of:
  262. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  263. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  264. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  265. """
  266. do_resize = do_resize if do_resize is not None else self.do_resize
  267. size = size if size is not None else self.size
  268. size = get_size_dict(size)
  269. resample = resample if resample is not None else self.resample
  270. do_rescale = do_rescale if do_rescale is not None else self.do_rescale
  271. rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
  272. do_normalize = do_normalize if do_normalize is not None else self.do_normalize
  273. image_mean = image_mean if image_mean is not None else self.image_mean
  274. image_std = image_std if image_std is not None else self.image_std
  275. apply_ocr = apply_ocr if apply_ocr is not None else self.apply_ocr
  276. ocr_lang = ocr_lang if ocr_lang is not None else self.ocr_lang
  277. tesseract_config = tesseract_config if tesseract_config is not None else self.tesseract_config
  278. images = make_list_of_images(images)
  279. if not valid_images(images):
  280. raise ValueError(
  281. "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
  282. "torch.Tensor, tf.Tensor or jax.ndarray."
  283. )
  284. validate_preprocess_arguments(
  285. do_rescale=do_rescale,
  286. rescale_factor=rescale_factor,
  287. do_normalize=do_normalize,
  288. image_mean=image_mean,
  289. image_std=image_std,
  290. do_resize=do_resize,
  291. size=size,
  292. resample=resample,
  293. )
  294. # All transformations expect numpy arrays.
  295. images = [to_numpy_array(image) for image in images]
  296. if is_scaled_image(images[0]) and do_rescale:
  297. logger.warning_once(
  298. "It looks like you are trying to rescale already rescaled images. If the input"
  299. " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
  300. )
  301. if input_data_format is None:
  302. # We assume that all images have the same channel dimension format.
  303. input_data_format = infer_channel_dimension_format(images[0])
  304. # Tesseract OCR to get words + normalized bounding boxes
  305. if apply_ocr:
  306. requires_backends(self, "pytesseract")
  307. words_batch = []
  308. boxes_batch = []
  309. for image in images:
  310. words, boxes = apply_tesseract(image, ocr_lang, tesseract_config, input_data_format=input_data_format)
  311. words_batch.append(words)
  312. boxes_batch.append(boxes)
  313. if do_resize:
  314. images = [
  315. self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
  316. for image in images
  317. ]
  318. if do_rescale:
  319. images = [
  320. self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
  321. for image in images
  322. ]
  323. if do_normalize:
  324. images = [
  325. self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
  326. for image in images
  327. ]
  328. images = [
  329. to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
  330. ]
  331. data = BatchFeature(data={"pixel_values": images}, tensor_type=return_tensors)
  332. if apply_ocr:
  333. data["words"] = words_batch
  334. data["boxes"] = boxes_batch
  335. return data