custom-layoutparser 9.9.9__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- custom_layoutparser-9.9.9.dist-info/METADATA +5 -0
- custom_layoutparser-9.9.9.dist-info/RECORD +36 -0
- custom_layoutparser-9.9.9.dist-info/WHEEL +5 -0
- custom_layoutparser-9.9.9.dist-info/top_level.txt +1 -0
- layoutparser/__init__.py +89 -0
- layoutparser/elements/__init__.py +25 -0
- layoutparser/elements/base.py +275 -0
- layoutparser/elements/errors.py +26 -0
- layoutparser/elements/layout.py +348 -0
- layoutparser/elements/layout_elements.py +1352 -0
- layoutparser/elements/utils.py +82 -0
- layoutparser/file_utils.py +235 -0
- layoutparser/io/__init__.py +2 -0
- layoutparser/io/basic.py +148 -0
- layoutparser/io/pdf.py +225 -0
- layoutparser/models/__init__.py +18 -0
- layoutparser/models/auto_layoutmodel.py +70 -0
- layoutparser/models/base_catalog.py +34 -0
- layoutparser/models/base_layoutmodel.py +88 -0
- layoutparser/models/detectron2/__init__.py +18 -0
- layoutparser/models/detectron2/catalog.py +142 -0
- layoutparser/models/detectron2/layoutmodel.py +168 -0
- layoutparser/models/effdet/__init__.py +16 -0
- layoutparser/models/effdet/catalog.py +70 -0
- layoutparser/models/effdet/layoutmodel.py +256 -0
- layoutparser/models/model_config.py +133 -0
- layoutparser/models/paddledetection/__init__.py +17 -0
- layoutparser/models/paddledetection/catalog.py +214 -0
- layoutparser/models/paddledetection/layoutmodel.py +297 -0
- layoutparser/ocr/__init__.py +16 -0
- layoutparser/ocr/base.py +41 -0
- layoutparser/ocr/gcv_agent.py +288 -0
- layoutparser/ocr/tesseract_agent.py +193 -0
- layoutparser/tools/__init__.py +5 -0
- layoutparser/tools/shape_operations.py +167 -0
- layoutparser/visualization.py +571 -0
|
@@ -0,0 +1,571 @@
|
|
|
1
|
+
# Copyright 2021 The Layout Parser team. All rights reserved.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
from typing import List, Optional, Union, Dict, Any, Tuple, Dict
|
|
16
|
+
import functools
|
|
17
|
+
import os
|
|
18
|
+
import sys
|
|
19
|
+
from itertools import cycle
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
from PIL import Image, ImageFont, ImageDraw, ImageColor
|
|
23
|
+
|
|
24
|
+
import layoutparser
|
|
25
|
+
from .elements import (
|
|
26
|
+
Layout,
|
|
27
|
+
Interval,
|
|
28
|
+
Rectangle,
|
|
29
|
+
TextBlock,
|
|
30
|
+
Quadrilateral,
|
|
31
|
+
)
|
|
32
|
+
from .elements.utils import cvt_coordinates_to_points
|
|
33
|
+
|
|
34
|
+
# We need to fix this ugly hack some time in the future
|
|
35
|
+
_lib_path = os.path.dirname(sys.modules[layoutparser.__package__].__file__)
|
|
36
|
+
_font_path = os.path.join(_lib_path, "misc", "NotoSerifCJKjp-Regular.otf")
|
|
37
|
+
|
|
38
|
+
DEFAULT_BOX_WIDTH_RATIO = 0.005
|
|
39
|
+
DEFAULT_OUTLINE_COLOR = "red"
|
|
40
|
+
DEAFULT_COLOR_PALETTE = "#f6bd60-#f7ede2-#f5cac3-#84a59d-#f28482"
|
|
41
|
+
# From https://coolors.co/f6bd60-f7ede2-f5cac3-84a59d-f28482
|
|
42
|
+
|
|
43
|
+
DEFAULT_FONT_PATH = _font_path
|
|
44
|
+
DEFAULT_FONT_SIZE = 15
|
|
45
|
+
DEFAULT_FONT_OBJECT = ImageFont.truetype(DEFAULT_FONT_PATH, DEFAULT_FONT_SIZE)
|
|
46
|
+
DEFAULT_TEXT_COLOR = "black"
|
|
47
|
+
DEFAULT_TEXT_BACKGROUND = "white"
|
|
48
|
+
|
|
49
|
+
__all__ = ["draw_box", "draw_text"]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _draw_vertical_text(
|
|
53
|
+
text,
|
|
54
|
+
image_font,
|
|
55
|
+
text_color,
|
|
56
|
+
text_background_color,
|
|
57
|
+
character_spacing=2,
|
|
58
|
+
space_width=1,
|
|
59
|
+
):
|
|
60
|
+
"""Helper function to draw text vertically.
|
|
61
|
+
Ref: https://github.com/Belval/TextRecognitionDataGenerator/blob/7f4c782c33993d2b6f712d01e86a2f342025f2df/trdg/computer_text_generator.py
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
space_height = int(image_font.getsize(" ")[1] * space_width)
|
|
65
|
+
|
|
66
|
+
char_heights = [
|
|
67
|
+
image_font.getsize(c)[1] if c != " " else space_height for c in text
|
|
68
|
+
]
|
|
69
|
+
text_width = max([image_font.getsize(c)[0] for c in text])
|
|
70
|
+
text_height = sum(char_heights) + character_spacing * len(text)
|
|
71
|
+
|
|
72
|
+
txt_img = Image.new("RGBA", (text_width, text_height), color=text_background_color)
|
|
73
|
+
txt_mask = Image.new("RGBA", (text_width, text_height), color=text_background_color)
|
|
74
|
+
|
|
75
|
+
txt_img_draw = ImageDraw.Draw(txt_img)
|
|
76
|
+
txt_mask_draw = ImageDraw.Draw(txt_mask)
|
|
77
|
+
|
|
78
|
+
for i, c in enumerate(text):
|
|
79
|
+
txt_img_draw.text(
|
|
80
|
+
(0, sum(char_heights[0:i]) + i * character_spacing),
|
|
81
|
+
c,
|
|
82
|
+
fill=text_color,
|
|
83
|
+
font=image_font,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
return txt_img.crop(txt_img.getbbox())
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _calculate_default_box_width(canvas):
|
|
90
|
+
return max(1, int(min(canvas.size) * DEFAULT_BOX_WIDTH_RATIO))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _create_font_object(font_size=None, font_path=None):
|
|
94
|
+
|
|
95
|
+
if font_size is None and font_path is None:
|
|
96
|
+
return DEFAULT_FONT_OBJECT
|
|
97
|
+
else:
|
|
98
|
+
return ImageFont.truetype(
|
|
99
|
+
font_path or DEFAULT_FONT_PATH, font_size or DEFAULT_FONT_SIZE
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _create_new_canvas(canvas, arrangement, text_background_color):
|
|
104
|
+
|
|
105
|
+
if arrangement == "lr":
|
|
106
|
+
new_canvas = Image.new(
|
|
107
|
+
"RGBA",
|
|
108
|
+
(canvas.width * 2, canvas.height),
|
|
109
|
+
color=text_background_color or DEFAULT_TEXT_BACKGROUND,
|
|
110
|
+
)
|
|
111
|
+
new_canvas.paste(canvas, (canvas.width, 0))
|
|
112
|
+
|
|
113
|
+
elif arrangement == "ud":
|
|
114
|
+
new_canvas = Image.new(
|
|
115
|
+
"RGBA",
|
|
116
|
+
(canvas.width, canvas.height * 2),
|
|
117
|
+
color=text_background_color or DEFAULT_TEXT_BACKGROUND,
|
|
118
|
+
)
|
|
119
|
+
new_canvas.paste(canvas, (0, canvas.height))
|
|
120
|
+
|
|
121
|
+
else:
|
|
122
|
+
raise ValueError(f"Invalid direction {arrangement}")
|
|
123
|
+
|
|
124
|
+
return new_canvas
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _create_color_palette(types):
|
|
128
|
+
return {
|
|
129
|
+
type: color
|
|
130
|
+
for type, color in zip(types, cycle(DEAFULT_COLOR_PALETTE.split("-")))
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _get_color_rgb(color_string: Any, alpha: float) -> Tuple[int, int, int, int]:
|
|
135
|
+
if color_string[0] == "#" and len(color_string) == 7:
|
|
136
|
+
# When color string is a hex string
|
|
137
|
+
color_hex = color_string.lstrip("#")
|
|
138
|
+
return (
|
|
139
|
+
*tuple(int(color_hex[i : i + 2], 16) for i in (0, 2, 4)),
|
|
140
|
+
int(255 * alpha),
|
|
141
|
+
)
|
|
142
|
+
else:
|
|
143
|
+
try:
|
|
144
|
+
rgb = ImageColor.getrgb(color_string)
|
|
145
|
+
return rgb + (int(255 * alpha),)
|
|
146
|
+
except:
|
|
147
|
+
# ImageColor.getrgb will throw an ValueError when the color is not
|
|
148
|
+
# a valid color string, even if it is in other formats supported by
|
|
149
|
+
# PIL. As such, we return the color as it is if the first two cases
|
|
150
|
+
# are not valid.
|
|
151
|
+
return color_string
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _draw_box_outline_on_handler(draw, block, color, width):
|
|
155
|
+
|
|
156
|
+
if not hasattr(block, "points"):
|
|
157
|
+
points = (cvt_coordinates_to_points(block.coordinates),)
|
|
158
|
+
else:
|
|
159
|
+
points = block.points
|
|
160
|
+
|
|
161
|
+
vertices = points.ravel().tolist()
|
|
162
|
+
drawing_vertices = vertices + vertices[:2]
|
|
163
|
+
|
|
164
|
+
draw.line(
|
|
165
|
+
drawing_vertices,
|
|
166
|
+
width=width,
|
|
167
|
+
fill=color,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _draw_transparent_box_on_handler(draw, block, color, alpha):
|
|
172
|
+
|
|
173
|
+
if hasattr(block, "points"):
|
|
174
|
+
vertices = [tuple(block) for block in block.points.tolist()]
|
|
175
|
+
else:
|
|
176
|
+
vertices = cvt_coordinates_to_points(block.coordinates)
|
|
177
|
+
|
|
178
|
+
draw.polygon(
|
|
179
|
+
vertices,
|
|
180
|
+
_get_color_rgb(color, alpha),
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def image_loader(func):
|
|
185
|
+
@functools.wraps(func)
|
|
186
|
+
def wrap(canvas, layout, *args, **kwargs):
|
|
187
|
+
|
|
188
|
+
if isinstance(canvas, Image.Image):
|
|
189
|
+
if canvas.mode != "RGB":
|
|
190
|
+
canvas = canvas.convert("RGB")
|
|
191
|
+
canvas = canvas.copy()
|
|
192
|
+
elif isinstance(canvas, np.ndarray):
|
|
193
|
+
canvas = Image.fromarray(canvas)
|
|
194
|
+
out = func(canvas, layout, *args, **kwargs)
|
|
195
|
+
return out
|
|
196
|
+
|
|
197
|
+
return wrap
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
@image_loader
|
|
201
|
+
def draw_transparent_box(
|
|
202
|
+
canvas: "Image",
|
|
203
|
+
blocks: Layout,
|
|
204
|
+
color_map: Dict = None,
|
|
205
|
+
alpha: float = 0.25,
|
|
206
|
+
) -> "Image":
|
|
207
|
+
"""Given the image, draw a series of transparent boxes based on the blocks,
|
|
208
|
+
coloring using the specified color_map.
|
|
209
|
+
"""
|
|
210
|
+
|
|
211
|
+
if color_map is None:
|
|
212
|
+
all_types = set([b.type for b in blocks if hasattr(b, "type")])
|
|
213
|
+
color_map = _create_color_palette(all_types)
|
|
214
|
+
|
|
215
|
+
canvas = canvas.copy()
|
|
216
|
+
draw = ImageDraw.Draw(canvas, "RGBA")
|
|
217
|
+
|
|
218
|
+
for block in blocks:
|
|
219
|
+
_draw_transparent_box_on_handler(draw, block, color_map[block.type], alpha)
|
|
220
|
+
|
|
221
|
+
return canvas
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
@image_loader
|
|
225
|
+
def draw_box(
|
|
226
|
+
canvas: Image.Image,
|
|
227
|
+
layout: Layout,
|
|
228
|
+
box_width: Optional[Union[List[int], int]] = None,
|
|
229
|
+
box_alpha: Optional[Union[List[float], float]] = None,
|
|
230
|
+
box_color: Optional[Union[List[str], str]] = None,
|
|
231
|
+
color_map: Optional[Dict] = None,
|
|
232
|
+
show_element_id: bool = False,
|
|
233
|
+
show_element_type: bool = False,
|
|
234
|
+
id_font_size: Optional[int] = None,
|
|
235
|
+
id_font_path: Optional[str] = None,
|
|
236
|
+
id_text_color: Optional[str] = None,
|
|
237
|
+
id_text_background_color: Optional[str] = None,
|
|
238
|
+
id_text_background_alpha: Optional[float] = 1,
|
|
239
|
+
):
|
|
240
|
+
"""Draw the layout region on the input canvas(image).
|
|
241
|
+
|
|
242
|
+
Args:
|
|
243
|
+
canvas (:obj:`~np.ndarray` or :obj:`~PIL.Image.Image`):
|
|
244
|
+
The canvas to draw the layout boxes.
|
|
245
|
+
layout (:obj:`Layout` or :obj:`list`):
|
|
246
|
+
The layout of the canvas to show.
|
|
247
|
+
box_width (:obj:`int` or :obj:`List[int]`, optional):
|
|
248
|
+
Set to change the width of the drawn layout box boundary.
|
|
249
|
+
Defaults to None, when the boundary is automatically
|
|
250
|
+
calculated as the the :const:`DEFAULT_BOX_WIDTH_RATIO`
|
|
251
|
+
* the maximum of (height, width) of the canvas.
|
|
252
|
+
If box_with is a list, it will assign different widths to
|
|
253
|
+
the corresponding layout object, and should have the same
|
|
254
|
+
length as the number of blocks in `layout`.
|
|
255
|
+
box_alpha (:obj:`float` or :obj:`List[float]`, optional):
|
|
256
|
+
A float or list of floats ranging from 0 to 1. Set to change
|
|
257
|
+
the alpha of the drawn layout box.
|
|
258
|
+
Defaults to 0 - the layout box will be fully transparent.
|
|
259
|
+
If box_alpha is a list of floats, it will assign different
|
|
260
|
+
alphas to the corresponding layout object, and should have
|
|
261
|
+
the same length as the number of blocks in `layout`.
|
|
262
|
+
box_color (:obj:`str` or :obj:`List[str]`, optional):
|
|
263
|
+
A string or a list of strings for box colors, e.g.,
|
|
264
|
+
`['red', 'green', 'blue']` or `'red'`.
|
|
265
|
+
If box_color is a list of strings, it will assign different
|
|
266
|
+
colors to the corresponding layout object, and should have
|
|
267
|
+
the same length as the number of blocks in `layout`.
|
|
268
|
+
Defaults to None. When `box_color` is set, it will override the
|
|
269
|
+
`color_map`.
|
|
270
|
+
color_map (dict, optional):
|
|
271
|
+
A map from `block.type` to the colors, e.g., `{1: 'red'}`.
|
|
272
|
+
You can set it to `{}` to use only the
|
|
273
|
+
:const:`DEFAULT_OUTLINE_COLOR` for the outlines.
|
|
274
|
+
Defaults to None, when a color palette is is automatically
|
|
275
|
+
created based on the input layout.
|
|
276
|
+
show_element_id (bool, optional):
|
|
277
|
+
Whether to display `block.id` on the top-left corner of
|
|
278
|
+
the block.
|
|
279
|
+
Defaults to False.
|
|
280
|
+
show_element_type (bool, optional):
|
|
281
|
+
Whether to display `block.type` on the top-left corner of
|
|
282
|
+
the block.
|
|
283
|
+
Defaults to False.
|
|
284
|
+
id_font_size (int, optional):
|
|
285
|
+
Set to change the font size used for drawing `block.id`.
|
|
286
|
+
Defaults to None, when the size is set to
|
|
287
|
+
:const:`DEFAULT_FONT_SIZE`.
|
|
288
|
+
id_font_path (:obj:`str`, optional):
|
|
289
|
+
Set to change the font used for drawing `block.id`.
|
|
290
|
+
Defaults to None, when the :const:`DEFAULT_FONT_OBJECT` is used.
|
|
291
|
+
id_text_color (:obj:`str`, optional):
|
|
292
|
+
Set to change the text color used for drawing `block.id`.
|
|
293
|
+
Defaults to None, when the color is set to
|
|
294
|
+
:const:`DEFAULT_TEXT_COLOR`.
|
|
295
|
+
id_text_background_color (:obj:`str`, optional):
|
|
296
|
+
Set to change the text region background used for drawing `block.id`.
|
|
297
|
+
Defaults to None, when the color is set to
|
|
298
|
+
:const:`DEFAULT_TEXT_BACKGROUND`.
|
|
299
|
+
id_text_background_alpha (:obj:`float`, optional):
|
|
300
|
+
A float range from 0 to 1. Set to change the alpha of the
|
|
301
|
+
drawn text.
|
|
302
|
+
Defaults to 1 - the text box will be solid.
|
|
303
|
+
Returns:
|
|
304
|
+
:obj:`PIL.Image.Image`:
|
|
305
|
+
A Image object containing the `layout` draw upon the input `canvas`.
|
|
306
|
+
"""
|
|
307
|
+
|
|
308
|
+
assert 0 <= id_text_background_alpha <= 1, ValueError(
|
|
309
|
+
f"The id_text_background_alpha value {id_text_background_alpha} is not within range [0,1]."
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
draw = ImageDraw.Draw(canvas, mode="RGBA")
|
|
313
|
+
|
|
314
|
+
id_text_background_color = id_text_background_color or DEFAULT_TEXT_BACKGROUND
|
|
315
|
+
id_text_color = id_text_color or DEFAULT_TEXT_COLOR
|
|
316
|
+
|
|
317
|
+
if show_element_id or show_element_type:
|
|
318
|
+
font_obj = _create_font_object(id_font_size, id_font_path)
|
|
319
|
+
|
|
320
|
+
if box_alpha is None:
|
|
321
|
+
box_alpha = [0] * len(layout)
|
|
322
|
+
else:
|
|
323
|
+
if isinstance(box_alpha, (float, int)):
|
|
324
|
+
box_alpha = [box_alpha] * len(layout)
|
|
325
|
+
|
|
326
|
+
if len(box_alpha) != len(layout):
|
|
327
|
+
raise ValueError(
|
|
328
|
+
f"The number of alphas {len(box_alpha)} is not equal to the number of blocks {len(layout)}"
|
|
329
|
+
)
|
|
330
|
+
if not all(0 <= a <= 1 for a in box_alpha):
|
|
331
|
+
raise ValueError(
|
|
332
|
+
f"The box_alpha value {box_alpha} is not within range [0,1]."
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
if box_width is None:
|
|
336
|
+
box_width = _calculate_default_box_width(canvas)
|
|
337
|
+
box_width = [box_width] * len(layout)
|
|
338
|
+
else:
|
|
339
|
+
if isinstance(box_width, (float, int)):
|
|
340
|
+
box_width = [box_width] * len(layout)
|
|
341
|
+
|
|
342
|
+
if len(box_width) != len(layout):
|
|
343
|
+
raise ValueError(
|
|
344
|
+
f"The number of widths {len(box_width)} is not equal to the number of blocks {len(layout)}"
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
if box_color is None:
|
|
348
|
+
if color_map is None:
|
|
349
|
+
all_types = set([b.type for b in layout if hasattr(b, "type")])
|
|
350
|
+
color_map = _create_color_palette(all_types)
|
|
351
|
+
box_color = [
|
|
352
|
+
DEFAULT_OUTLINE_COLOR
|
|
353
|
+
if not isinstance(ele, TextBlock)
|
|
354
|
+
else color_map.get(ele.type, DEFAULT_OUTLINE_COLOR)
|
|
355
|
+
for ele in layout
|
|
356
|
+
]
|
|
357
|
+
else:
|
|
358
|
+
if isinstance(box_color, str):
|
|
359
|
+
box_color = [box_color] * len(layout)
|
|
360
|
+
|
|
361
|
+
if len(box_color) != len(layout):
|
|
362
|
+
raise ValueError(
|
|
363
|
+
f"The number of colors {len(box_color)} is not equal to the number of blocks {len(layout)}"
|
|
364
|
+
)
|
|
365
|
+
|
|
366
|
+
# A post check of the lengths of the input lists
|
|
367
|
+
# To support more versions of python, we do not use
|
|
368
|
+
# zip(*, strict=True)
|
|
369
|
+
assert len(layout) == len(box_color) == len(box_alpha) == len(box_width)
|
|
370
|
+
|
|
371
|
+
for idx, (ele, color, alpha, width) in enumerate(
|
|
372
|
+
zip(layout, box_color, box_alpha, box_width)
|
|
373
|
+
):
|
|
374
|
+
|
|
375
|
+
if isinstance(ele, Interval):
|
|
376
|
+
ele = ele.put_on_canvas(canvas)
|
|
377
|
+
|
|
378
|
+
if width > 0:
|
|
379
|
+
_draw_box_outline_on_handler(draw, ele, color, width)
|
|
380
|
+
|
|
381
|
+
_draw_transparent_box_on_handler(draw, ele, color, alpha)
|
|
382
|
+
|
|
383
|
+
if show_element_id or show_element_type:
|
|
384
|
+
text = ""
|
|
385
|
+
if show_element_id:
|
|
386
|
+
ele_id = ele.id or idx
|
|
387
|
+
text += str(ele_id)
|
|
388
|
+
if show_element_type:
|
|
389
|
+
text = str(ele.type) if not text else text + ": " + str(ele.type)
|
|
390
|
+
|
|
391
|
+
start_x, start_y = ele.coordinates[:2]
|
|
392
|
+
text_w, text_h = font_obj.getsize(text)
|
|
393
|
+
|
|
394
|
+
text_box_object = Rectangle(
|
|
395
|
+
start_x, start_y, start_x + text_w, start_y + text_h
|
|
396
|
+
)
|
|
397
|
+
# Add a small background for the text
|
|
398
|
+
|
|
399
|
+
_draw_transparent_box_on_handler(
|
|
400
|
+
draw,
|
|
401
|
+
text_box_object,
|
|
402
|
+
id_text_background_color,
|
|
403
|
+
id_text_background_alpha,
|
|
404
|
+
)
|
|
405
|
+
|
|
406
|
+
# Draw the ids
|
|
407
|
+
draw.text(
|
|
408
|
+
(start_x, start_y),
|
|
409
|
+
text,
|
|
410
|
+
fill=id_text_color,
|
|
411
|
+
font=font_obj,
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
return canvas
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
@image_loader
|
|
418
|
+
def draw_text(
|
|
419
|
+
canvas,
|
|
420
|
+
layout,
|
|
421
|
+
arrangement: str = "lr",
|
|
422
|
+
font_size: Optional[int] = None,
|
|
423
|
+
font_path: Optional[str] = None,
|
|
424
|
+
text_color: Optional[str] = None,
|
|
425
|
+
text_background_color: Optional[str] = None,
|
|
426
|
+
text_background_alpha: Optional[float] = None,
|
|
427
|
+
vertical_text: bool = False,
|
|
428
|
+
with_box_on_text: bool = False,
|
|
429
|
+
text_box_width: Optional[int] = None,
|
|
430
|
+
text_box_color: Optional[str] = None,
|
|
431
|
+
text_box_alpha: Optional[float] = None,
|
|
432
|
+
with_layout: bool = False,
|
|
433
|
+
**kwargs,
|
|
434
|
+
):
|
|
435
|
+
"""Draw the (detected) text in the `layout` according to
|
|
436
|
+
their coordinates next to the input `canvas` (image) for better comparison.
|
|
437
|
+
|
|
438
|
+
Args:
|
|
439
|
+
canvas (:obj:`~np.ndarray` or :obj:`~PIL.Image.Image`):
|
|
440
|
+
The canvas to draw the layout boxes.
|
|
441
|
+
layout (:obj:`Layout` or :obj:`list`):
|
|
442
|
+
The layout of the canvas to show.
|
|
443
|
+
arrangement (`{'lr', 'ud'}`, optional):
|
|
444
|
+
The arrangement of the drawn text canvas and the original
|
|
445
|
+
image canvas:
|
|
446
|
+
* `lr` - left and right
|
|
447
|
+
* `ud` - up and down
|
|
448
|
+
Defaults to 'lr'.
|
|
449
|
+
font_size (:obj:`str`, optional):
|
|
450
|
+
Set to change the size of the font used for
|
|
451
|
+
drawing `block.text`.
|
|
452
|
+
Defaults to None, when the size is set to
|
|
453
|
+
:const:`DEFAULT_FONT_SIZE`.
|
|
454
|
+
font_path (:obj:`str`, optional):
|
|
455
|
+
Set to change the font used for drawing `block.text`.
|
|
456
|
+
Defaults to None, when the :const:`DEFAULT_FONT_OBJECT` is used.
|
|
457
|
+
text_color ([type], optional):
|
|
458
|
+
Set to change the text color used for drawing `block.text`.
|
|
459
|
+
Defaults to None, when the color is set to
|
|
460
|
+
:const:`DEFAULT_TEXT_COLOR`.
|
|
461
|
+
text_background_color ([type], optional):
|
|
462
|
+
Set to change the text region background used for drawing
|
|
463
|
+
`block.text`.
|
|
464
|
+
Defaults to None, when the color is set to
|
|
465
|
+
:const:`DEFAULT_TEXT_BACKGROUND`.
|
|
466
|
+
text_background_alpha (:obj:`float`, optional):
|
|
467
|
+
A float range from 0 to 1. Set to change the alpha of the
|
|
468
|
+
background of the canvas.
|
|
469
|
+
Defaults to 1 - the text box will be solid.
|
|
470
|
+
vertical_text (bool, optional):
|
|
471
|
+
Whether the text in a block should be drawn vertically.
|
|
472
|
+
Defaults to False.
|
|
473
|
+
with_box_on_text (bool, optional):
|
|
474
|
+
Whether to draw the layout box boundary of a text region
|
|
475
|
+
on the text canvas.
|
|
476
|
+
Defaults to False.
|
|
477
|
+
text_box_width (:obj:`int`, optional):
|
|
478
|
+
Set to change the width of the drawn layout box boundary.
|
|
479
|
+
Defaults to None, when the boundary is automatically
|
|
480
|
+
calculated as the the :const:`DEFAULT_BOX_WIDTH_RATIO`
|
|
481
|
+
* the maximum of (height, width) of the canvas.
|
|
482
|
+
text_box_alpha (:obj:`float`, optional):
|
|
483
|
+
A float range from 0 to 1. Set to change the alpha of the
|
|
484
|
+
drawn text box.
|
|
485
|
+
Defaults to 0 - the text box will be fully transparent.
|
|
486
|
+
text_box_color (:obj:`int`, optional):
|
|
487
|
+
Set to change the color of the drawn layout box boundary.
|
|
488
|
+
Defaults to None, when the color is set to
|
|
489
|
+
:const:`DEFAULT_OUTLINE_COLOR`.
|
|
490
|
+
with_layout (bool, optional):
|
|
491
|
+
Whether to draw the layout boxes on the input (image) canvas.
|
|
492
|
+
Defaults to False.
|
|
493
|
+
When set to true, you can pass in the arguments in
|
|
494
|
+
:obj:`draw_box` to change the style of the drawn layout boxes.
|
|
495
|
+
|
|
496
|
+
Returns:
|
|
497
|
+
:obj:`PIL.Image.Image`:
|
|
498
|
+
A Image object containing the drawn text from `layout`.
|
|
499
|
+
"""
|
|
500
|
+
|
|
501
|
+
if text_background_alpha is None:
|
|
502
|
+
text_background_alpha = 1
|
|
503
|
+
if text_box_alpha is None:
|
|
504
|
+
text_box_alpha = 0
|
|
505
|
+
|
|
506
|
+
assert 0 <= text_background_alpha <= 1, ValueError(
|
|
507
|
+
f"The text_background_color value {text_background_alpha} is not within range [0,1]."
|
|
508
|
+
)
|
|
509
|
+
assert 0 <= text_box_alpha <= 1, ValueError(
|
|
510
|
+
f"The text_box_alpha value {text_box_alpha} is not within range [0,1]."
|
|
511
|
+
)
|
|
512
|
+
|
|
513
|
+
if with_box_on_text:
|
|
514
|
+
if text_box_width is None:
|
|
515
|
+
text_box_width = _calculate_default_box_width(canvas)
|
|
516
|
+
|
|
517
|
+
if with_layout:
|
|
518
|
+
canvas = draw_box(canvas, layout, **kwargs)
|
|
519
|
+
|
|
520
|
+
font_obj = _create_font_object(font_size, font_path)
|
|
521
|
+
text_box_color = text_box_color or DEFAULT_OUTLINE_COLOR
|
|
522
|
+
text_color = text_color or DEFAULT_TEXT_COLOR
|
|
523
|
+
text_background_color = text_background_color or DEFAULT_TEXT_BACKGROUND
|
|
524
|
+
|
|
525
|
+
canvas = _create_new_canvas(
|
|
526
|
+
canvas,
|
|
527
|
+
arrangement,
|
|
528
|
+
_get_color_rgb(text_background_color, text_background_alpha),
|
|
529
|
+
)
|
|
530
|
+
draw = ImageDraw.Draw(canvas, "RGBA")
|
|
531
|
+
|
|
532
|
+
for idx, ele in enumerate(layout):
|
|
533
|
+
|
|
534
|
+
if with_box_on_text:
|
|
535
|
+
modified_box = ele.pad(right=text_box_width, bottom=text_box_width)
|
|
536
|
+
|
|
537
|
+
_draw_box_outline_on_handler(
|
|
538
|
+
draw, modified_box, text_box_color, text_box_width
|
|
539
|
+
)
|
|
540
|
+
_draw_transparent_box_on_handler(
|
|
541
|
+
draw, modified_box, text_box_color, text_box_alpha
|
|
542
|
+
)
|
|
543
|
+
|
|
544
|
+
if not hasattr(ele, "text") or ele.text == "":
|
|
545
|
+
continue
|
|
546
|
+
|
|
547
|
+
(start_x, start_y) = ele.coordinates[:2]
|
|
548
|
+
if not vertical_text:
|
|
549
|
+
draw.text(
|
|
550
|
+
(start_x, start_y),
|
|
551
|
+
ele.text,
|
|
552
|
+
font=font_obj,
|
|
553
|
+
fill=text_color,
|
|
554
|
+
)
|
|
555
|
+
else:
|
|
556
|
+
text_segment = _draw_vertical_text(
|
|
557
|
+
ele.text,
|
|
558
|
+
font_obj,
|
|
559
|
+
text_color,
|
|
560
|
+
_get_color_rgb(text_background_color, text_background_alpha),
|
|
561
|
+
)
|
|
562
|
+
|
|
563
|
+
if with_box_on_text:
|
|
564
|
+
# Avoid cover the box regions
|
|
565
|
+
canvas.paste(
|
|
566
|
+
text_segment, (start_x + text_box_width, start_y + text_box_width)
|
|
567
|
+
)
|
|
568
|
+
else:
|
|
569
|
+
canvas.paste(text_segment, (start_x, start_y))
|
|
570
|
+
|
|
571
|
+
return canvas
|