image_processing_layoutlmv2.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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 LayoutLMv2."""
  16. from typing import Dict, Optional, 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, resize, to_channel_dimension_format, to_pil_image
  20. from ...image_utils import (
  21. ChannelDimension,
  22. ImageInput,
  23. PILImageResampling,
  24. infer_channel_dimension_format,
  25. make_list_of_images,
  26. to_numpy_array,
  27. valid_images,
  28. validate_preprocess_arguments,
  29. )
  30. from ...utils import (
  31. TensorType,
  32. filter_out_non_signature_kwargs,
  33. is_pytesseract_available,
  34. is_vision_available,
  35. logging,
  36. requires_backends,
  37. )
  38. if is_vision_available():
  39. import PIL
  40. # soft dependency
  41. if is_pytesseract_available():
  42. import pytesseract
  43. logger = logging.get_logger(__name__)
  44. def normalize_box(box, width, height):
  45. return [
  46. int(1000 * (box[0] / width)),
  47. int(1000 * (box[1] / height)),
  48. int(1000 * (box[2] / width)),
  49. int(1000 * (box[3] / height)),
  50. ]
  51. def apply_tesseract(
  52. image: np.ndarray,
  53. lang: Optional[str],
  54. tesseract_config: Optional[str] = None,
  55. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  56. ):
  57. """Applies Tesseract OCR on a document image, and returns recognized words + normalized bounding boxes."""
  58. tesseract_config = tesseract_config if tesseract_config is not None else ""
  59. # apply OCR
  60. pil_image = to_pil_image(image, input_data_format=input_data_format)
  61. image_width, image_height = pil_image.size
  62. data = pytesseract.image_to_data(pil_image, lang=lang, output_type="dict", config=tesseract_config)
  63. words, left, top, width, height = data["text"], data["left"], data["top"], data["width"], data["height"]
  64. # filter empty words and corresponding coordinates
  65. irrelevant_indices = [idx for idx, word in enumerate(words) if not word.strip()]
  66. words = [word for idx, word in enumerate(words) if idx not in irrelevant_indices]
  67. left = [coord for idx, coord in enumerate(left) if idx not in irrelevant_indices]
  68. top = [coord for idx, coord in enumerate(top) if idx not in irrelevant_indices]
  69. width = [coord for idx, coord in enumerate(width) if idx not in irrelevant_indices]
  70. height = [coord for idx, coord in enumerate(height) if idx not in irrelevant_indices]
  71. # turn coordinates into (left, top, left+width, top+height) format
  72. actual_boxes = []
  73. for x, y, w, h in zip(left, top, width, height):
  74. actual_box = [x, y, x + w, y + h]
  75. actual_boxes.append(actual_box)
  76. # finally, normalize the bounding boxes
  77. normalized_boxes = []
  78. for box in actual_boxes:
  79. normalized_boxes.append(normalize_box(box, image_width, image_height))
  80. assert len(words) == len(normalized_boxes), "Not as many words as there are bounding boxes"
  81. return words, normalized_boxes
  82. class LayoutLMv2ImageProcessor(BaseImageProcessor):
  83. r"""
  84. Constructs a LayoutLMv2 image processor.
  85. Args:
  86. do_resize (`bool`, *optional*, defaults to `True`):
  87. Whether to resize the image's (height, width) dimensions to `(size["height"], size["width"])`. Can be
  88. overridden by `do_resize` in `preprocess`.
  89. size (`Dict[str, int]` *optional*, defaults to `{"height": 224, "width": 224}`):
  90. Size of the image after resizing. Can be overridden by `size` in `preprocess`.
  91. resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
  92. Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
  93. `preprocess` method.
  94. apply_ocr (`bool`, *optional*, defaults to `True`):
  95. Whether to apply the Tesseract OCR engine to get words + normalized bounding boxes. Can be overridden by
  96. `apply_ocr` in `preprocess`.
  97. ocr_lang (`str`, *optional*):
  98. The language, specified by its ISO code, to be used by the Tesseract OCR engine. By default, English is
  99. used. Can be overridden by `ocr_lang` in `preprocess`.
  100. tesseract_config (`str`, *optional*, defaults to `""`):
  101. Any additional custom configuration flags that are forwarded to the `config` parameter when calling
  102. Tesseract. For example: '--psm 6'. Can be overridden by `tesseract_config` in `preprocess`.
  103. """
  104. model_input_names = ["pixel_values"]
  105. def __init__(
  106. self,
  107. do_resize: bool = True,
  108. size: Dict[str, int] = None,
  109. resample: PILImageResampling = PILImageResampling.BILINEAR,
  110. apply_ocr: bool = True,
  111. ocr_lang: Optional[str] = None,
  112. tesseract_config: Optional[str] = "",
  113. **kwargs,
  114. ) -> None:
  115. super().__init__(**kwargs)
  116. size = size if size is not None else {"height": 224, "width": 224}
  117. size = get_size_dict(size)
  118. self.do_resize = do_resize
  119. self.size = size
  120. self.resample = resample
  121. self.apply_ocr = apply_ocr
  122. self.ocr_lang = ocr_lang
  123. self.tesseract_config = tesseract_config
  124. # Copied from transformers.models.vit.image_processing_vit.ViTImageProcessor.resize
  125. def resize(
  126. self,
  127. image: np.ndarray,
  128. size: Dict[str, int],
  129. resample: PILImageResampling = PILImageResampling.BILINEAR,
  130. data_format: Optional[Union[str, ChannelDimension]] = None,
  131. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  132. **kwargs,
  133. ) -> np.ndarray:
  134. """
  135. Resize an image to `(size["height"], size["width"])`.
  136. Args:
  137. image (`np.ndarray`):
  138. Image to resize.
  139. size (`Dict[str, int]`):
  140. Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
  141. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
  142. `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
  143. data_format (`ChannelDimension` or `str`, *optional*):
  144. The channel dimension format for the output image. If unset, the channel dimension format of the input
  145. image is used. Can be one of:
  146. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  147. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  148. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  149. input_data_format (`ChannelDimension` or `str`, *optional*):
  150. The channel dimension format for the input image. If unset, the channel dimension format is inferred
  151. from the input image. Can be one of:
  152. - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  153. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  154. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
  155. Returns:
  156. `np.ndarray`: The resized image.
  157. """
  158. size = get_size_dict(size)
  159. if "height" not in size or "width" not in size:
  160. raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
  161. output_size = (size["height"], size["width"])
  162. return resize(
  163. image,
  164. size=output_size,
  165. resample=resample,
  166. data_format=data_format,
  167. input_data_format=input_data_format,
  168. **kwargs,
  169. )
  170. @filter_out_non_signature_kwargs()
  171. def preprocess(
  172. self,
  173. images: ImageInput,
  174. do_resize: bool = None,
  175. size: Dict[str, int] = None,
  176. resample: PILImageResampling = None,
  177. apply_ocr: bool = None,
  178. ocr_lang: Optional[str] = None,
  179. tesseract_config: Optional[str] = None,
  180. return_tensors: Optional[Union[str, TensorType]] = None,
  181. data_format: ChannelDimension = ChannelDimension.FIRST,
  182. input_data_format: Optional[Union[str, ChannelDimension]] = None,
  183. ) -> PIL.Image.Image:
  184. """
  185. Preprocess an image or batch of images.
  186. Args:
  187. images (`ImageInput`):
  188. Image to preprocess.
  189. do_resize (`bool`, *optional*, defaults to `self.do_resize`):
  190. Whether to resize the image.
  191. size (`Dict[str, int]`, *optional*, defaults to `self.size`):
  192. Desired size of the output image after resizing.
  193. resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
  194. Resampling filter to use if resizing the image. This can be one of the enum `PIL.Image` resampling
  195. filter. Only has an effect if `do_resize` is set to `True`.
  196. apply_ocr (`bool`, *optional*, defaults to `self.apply_ocr`):
  197. Whether to apply the Tesseract OCR engine to get words + normalized bounding boxes.
  198. ocr_lang (`str`, *optional*, defaults to `self.ocr_lang`):
  199. The language, specified by its ISO code, to be used by the Tesseract OCR engine. By default, English is
  200. used.
  201. tesseract_config (`str`, *optional*, defaults to `self.tesseract_config`):
  202. Any additional custom configuration flags that are forwarded to the `config` parameter when calling
  203. Tesseract.
  204. return_tensors (`str` or `TensorType`, *optional*):
  205. The type of tensors to return. Can be one of:
  206. - Unset: Return a list of `np.ndarray`.
  207. - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
  208. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
  209. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
  210. - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
  211. data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
  212. The channel dimension format for the output image. Can be one of:
  213. - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
  214. - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
  215. """
  216. do_resize = do_resize if do_resize is not None else self.do_resize
  217. size = size if size is not None else self.size
  218. size = get_size_dict(size)
  219. resample = resample if resample is not None else self.resample
  220. apply_ocr = apply_ocr if apply_ocr is not None else self.apply_ocr
  221. ocr_lang = ocr_lang if ocr_lang is not None else self.ocr_lang
  222. tesseract_config = tesseract_config if tesseract_config is not None else self.tesseract_config
  223. images = make_list_of_images(images)
  224. if not valid_images(images):
  225. raise ValueError(
  226. "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
  227. "torch.Tensor, tf.Tensor or jax.ndarray."
  228. )
  229. validate_preprocess_arguments(
  230. do_resize=do_resize,
  231. size=size,
  232. resample=resample,
  233. )
  234. # All transformations expect numpy arrays.
  235. images = [to_numpy_array(image) for image in images]
  236. if input_data_format is None:
  237. # We assume that all images have the same channel dimension format.
  238. input_data_format = infer_channel_dimension_format(images[0])
  239. if apply_ocr:
  240. requires_backends(self, "pytesseract")
  241. words_batch = []
  242. boxes_batch = []
  243. for image in images:
  244. words, boxes = apply_tesseract(image, ocr_lang, tesseract_config, input_data_format=input_data_format)
  245. words_batch.append(words)
  246. boxes_batch.append(boxes)
  247. if do_resize:
  248. images = [
  249. self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
  250. for image in images
  251. ]
  252. # flip color channels from RGB to BGR (as Detectron2 requires this)
  253. images = [flip_channel_order(image, input_data_format=input_data_format) for image in images]
  254. images = [
  255. to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
  256. ]
  257. data = BatchFeature(data={"pixel_values": images}, tensor_type=return_tensors)
  258. if apply_ocr:
  259. data["words"] = words_batch
  260. data["boxes"] = boxes_batch
  261. return data