python-doctr 1.0.1__py3-none-any.whl → 1.2.0__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.
- doctr/cli/__init__.py +0 -0
- doctr/cli/main.py +669 -0
- doctr/datasets/__init__.py +2 -0
- doctr/datasets/coco_text.py +4 -2
- doctr/datasets/cord.py +2 -1
- doctr/datasets/datasets/base.py +12 -24
- doctr/datasets/datasets/pytorch.py +14 -4
- doctr/datasets/detection.py +14 -3
- doctr/datasets/doc_artefacts.py +2 -1
- doctr/datasets/funsd.py +2 -1
- doctr/datasets/generator/base.py +121 -37
- doctr/datasets/generator/pytorch.py +5 -6
- doctr/datasets/ic03.py +9 -7
- doctr/datasets/ic13.py +4 -2
- doctr/datasets/iiit5k.py +2 -1
- doctr/datasets/iiithws.py +4 -2
- doctr/datasets/imgur5k.py +4 -2
- doctr/datasets/layout.py +129 -0
- doctr/datasets/mjsynth.py +4 -2
- doctr/datasets/ocr.py +2 -1
- doctr/datasets/orientation.py +2 -1
- doctr/datasets/recognition.py +5 -4
- doctr/datasets/sroie.py +2 -1
- doctr/datasets/svhn.py +2 -1
- doctr/datasets/svt.py +10 -8
- doctr/datasets/synthtext.py +2 -1
- doctr/datasets/table_structure.py +97 -0
- doctr/datasets/utils.py +104 -21
- doctr/datasets/vocabs.py +320 -148
- doctr/datasets/wildreceipt.py +4 -2
- doctr/file_utils.py +3 -1
- doctr/io/__init__.py +3 -0
- doctr/io/elements.py +381 -271
- doctr/io/exporters.py +1915 -0
- doctr/io/figures.py +313 -0
- doctr/io/image/base.py +54 -7
- doctr/io/image/pytorch.py +13 -5
- doctr/io/pdf.py +6 -5
- doctr/io/reader.py +268 -18
- doctr/io/sources.py +636 -0
- doctr/models/__init__.py +3 -0
- doctr/models/_utils.py +206 -13
- doctr/models/builder.py +590 -137
- doctr/models/classification/__init__.py +3 -0
- doctr/models/classification/hgnetv2/__init__.py +1 -0
- doctr/models/classification/hgnetv2/pytorch.py +352 -0
- doctr/models/classification/magc_resnet/pytorch.py +1 -1
- doctr/models/classification/mobilenet/pytorch.py +6 -6
- doctr/models/classification/predictor/pytorch.py +34 -2
- doctr/models/classification/resnet/pytorch.py +5 -5
- doctr/models/classification/starnet/__init__.py +1 -0
- doctr/models/classification/starnet/pytorch.py +202 -0
- doctr/models/classification/textnet/pytorch.py +6 -5
- doctr/models/classification/vgg/pytorch.py +3 -2
- doctr/models/classification/vip/layers/pytorch.py +4 -4
- doctr/models/classification/vip/pytorch.py +4 -4
- doctr/models/classification/vit/pytorch.py +3 -3
- doctr/models/classification/vit_det/__init__.py +1 -0
- doctr/models/classification/vit_det/layers/__init__.py +1 -0
- doctr/models/classification/vit_det/layers/pytorch.py +215 -0
- doctr/models/classification/vit_det/pytorch.py +346 -0
- doctr/models/classification/zoo.py +14 -2
- doctr/models/detection/_utils/base.py +23 -7
- doctr/models/detection/core.py +32 -18
- doctr/models/detection/differentiable_binarization/base.py +23 -9
- doctr/models/detection/differentiable_binarization/pytorch.py +10 -4
- doctr/models/detection/fast/base.py +22 -6
- doctr/models/detection/fast/pytorch.py +24 -11
- doctr/models/detection/linknet/base.py +22 -6
- doctr/models/detection/linknet/pytorch.py +10 -3
- doctr/models/detection/predictor/pytorch.py +43 -2
- doctr/models/detection/zoo.py +6 -2
- doctr/models/factory/hub.py +59 -41
- doctr/models/formula/__init__.py +2 -0
- doctr/models/formula/formulanet/__init__.py +2 -0
- doctr/models/formula/formulanet/base.py +70 -0
- doctr/models/formula/formulanet/pytorch.py +587 -0
- doctr/models/formula/predictor/__init__.py +1 -0
- doctr/models/formula/predictor/pytorch.py +132 -0
- doctr/models/formula/zoo.py +102 -0
- doctr/models/kie_predictor/base.py +23 -1
- doctr/models/kie_predictor/pytorch.py +87 -15
- doctr/models/layout/__init__.py +2 -0
- doctr/models/layout/lw_detr/__init__.py +1 -0
- doctr/models/layout/lw_detr/base.py +309 -0
- doctr/models/layout/lw_detr/layers/__init__.py +1 -0
- doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
- doctr/models/layout/lw_detr/pytorch.py +895 -0
- doctr/models/layout/predictor/__init__.py +1 -0
- doctr/models/layout/predictor/pytorch.py +114 -0
- doctr/models/layout/zoo.py +94 -0
- doctr/models/modules/layers/pytorch.py +139 -3
- doctr/models/modules/transformer/pytorch.py +151 -31
- doctr/models/predictor/base.py +415 -17
- doctr/models/predictor/pytorch.py +109 -12
- doctr/models/preprocessor/pytorch.py +82 -25
- doctr/models/reading_order/__init__.py +1 -0
- doctr/models/reading_order/base.py +1127 -0
- doctr/models/recognition/core.py +14 -1
- doctr/models/recognition/crnn/pytorch.py +40 -16
- doctr/models/recognition/master/base.py +4 -1
- doctr/models/recognition/master/pytorch.py +84 -22
- doctr/models/recognition/parseq/base.py +4 -1
- doctr/models/recognition/parseq/pytorch.py +126 -25
- doctr/models/recognition/predictor/_utils.py +131 -14
- doctr/models/recognition/predictor/pytorch.py +68 -12
- doctr/models/recognition/sar/pytorch.py +21 -7
- doctr/models/recognition/utils.py +80 -50
- doctr/models/recognition/viptr/pytorch.py +38 -14
- doctr/models/recognition/vitstr/base.py +4 -1
- doctr/models/recognition/vitstr/pytorch.py +11 -7
- doctr/models/recognition/zoo.py +36 -9
- doctr/models/table_structure/__init__.py +2 -0
- doctr/models/table_structure/grid.py +430 -0
- doctr/models/table_structure/predictor/__init__.py +1 -0
- doctr/models/table_structure/predictor/pytorch.py +231 -0
- doctr/models/table_structure/tablecenternet/__init__.py +2 -0
- doctr/models/table_structure/tablecenternet/base.py +675 -0
- doctr/models/table_structure/tablecenternet/pytorch.py +525 -0
- doctr/models/table_structure/zoo.py +87 -0
- doctr/models/utils/pytorch.py +381 -25
- doctr/models/zoo.py +141 -4
- doctr/transforms/functional/base.py +6 -0
- doctr/transforms/functional/pytorch.py +134 -6
- doctr/transforms/modules/base.py +261 -82
- doctr/transforms/modules/pytorch.py +396 -76
- doctr/utils/common_types.py +21 -1
- doctr/utils/data.py +24 -11
- doctr/utils/fonts.py +64 -17
- doctr/utils/geometry.py +167 -28
- doctr/utils/metrics.py +481 -19
- doctr/utils/multithreading.py +127 -4
- doctr/utils/reconstitution.py +696 -132
- doctr/utils/visualization.py +73 -10
- doctr/version.py +1 -1
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/METADATA +119 -249
- python_doctr-1.2.0.dist-info/RECORD +191 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
- python_doctr-1.2.0.dist-info/entry_points.txt +2 -0
- python_doctr-1.0.1.dist-info/RECORD +0 -149
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
doctr/models/zoo.py
CHANGED
|
@@ -5,10 +5,14 @@
|
|
|
5
5
|
|
|
6
6
|
from typing import Any
|
|
7
7
|
|
|
8
|
+
from ._utils import ConfidenceAggregation, _resolve_confidence_aggregation
|
|
8
9
|
from .detection.zoo import detection_predictor
|
|
10
|
+
from .formula.zoo import formula_predictor
|
|
9
11
|
from .kie_predictor import KIEPredictor
|
|
12
|
+
from .layout.zoo import layout_predictor
|
|
10
13
|
from .predictor import OCRPredictor
|
|
11
14
|
from .recognition.zoo import recognition_predictor
|
|
15
|
+
from .table_structure.zoo import table_predictor
|
|
12
16
|
|
|
13
17
|
__all__ = ["ocr_predictor", "kie_predictor"]
|
|
14
18
|
|
|
@@ -26,8 +30,18 @@ def _predictor(
|
|
|
26
30
|
detect_orientation: bool = False,
|
|
27
31
|
straighten_pages: bool = False,
|
|
28
32
|
detect_language: bool = False,
|
|
33
|
+
detect_layout: bool = False,
|
|
34
|
+
layout_arch: Any = "lw_detr_s",
|
|
35
|
+
ignore_regions: list[str] | None = None,
|
|
36
|
+
detect_tables: bool = False,
|
|
37
|
+
detect_formulas: bool = False,
|
|
38
|
+
confidence_aggregation: ConfidenceAggregation | None = None,
|
|
29
39
|
**kwargs,
|
|
30
40
|
) -> OCRPredictor:
|
|
41
|
+
if confidence_aggregation is not None:
|
|
42
|
+
# Fail before building the models
|
|
43
|
+
_resolve_confidence_aggregation(confidence_aggregation)
|
|
44
|
+
|
|
31
45
|
# Detection
|
|
32
46
|
det_predictor = detection_predictor(
|
|
33
47
|
det_arch,
|
|
@@ -45,6 +59,46 @@ def _predictor(
|
|
|
45
59
|
pretrained=pretrained,
|
|
46
60
|
pretrained_backbone=pretrained_backbone,
|
|
47
61
|
batch_size=reco_bs,
|
|
62
|
+
confidence_aggregation=confidence_aggregation,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
# Layout - required for table and formula recognition, so build it whenever one of them is requested
|
|
66
|
+
layout_pred = (
|
|
67
|
+
layout_predictor(
|
|
68
|
+
layout_arch,
|
|
69
|
+
pretrained=pretrained,
|
|
70
|
+
assume_straight_pages=assume_straight_pages,
|
|
71
|
+
preserve_aspect_ratio=preserve_aspect_ratio,
|
|
72
|
+
symmetric_pad=symmetric_pad,
|
|
73
|
+
batch_size=det_bs,
|
|
74
|
+
)
|
|
75
|
+
if (detect_layout or detect_tables or detect_formulas)
|
|
76
|
+
else None
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
# Table structure - optional, applied on the cropped table regions found by the layout model
|
|
80
|
+
table_pred = (
|
|
81
|
+
table_predictor(
|
|
82
|
+
"tablecenternet",
|
|
83
|
+
pretrained=pretrained,
|
|
84
|
+
assume_straight_pages=assume_straight_pages,
|
|
85
|
+
preserve_aspect_ratio=preserve_aspect_ratio,
|
|
86
|
+
symmetric_pad=symmetric_pad,
|
|
87
|
+
batch_size=det_bs,
|
|
88
|
+
)
|
|
89
|
+
if detect_tables
|
|
90
|
+
else None
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
# Formula recognition - optional, applied on the cropped formula regions found by the layout model
|
|
94
|
+
formula_pred = (
|
|
95
|
+
formula_predictor(
|
|
96
|
+
"formulanet",
|
|
97
|
+
pretrained=pretrained,
|
|
98
|
+
pretrained_backbone=pretrained_backbone,
|
|
99
|
+
)
|
|
100
|
+
if detect_formulas
|
|
101
|
+
else None
|
|
48
102
|
)
|
|
49
103
|
|
|
50
104
|
return OCRPredictor(
|
|
@@ -56,6 +110,10 @@ def _predictor(
|
|
|
56
110
|
detect_orientation=detect_orientation,
|
|
57
111
|
straighten_pages=straighten_pages,
|
|
58
112
|
detect_language=detect_language,
|
|
113
|
+
layout_predictor=layout_pred,
|
|
114
|
+
table_predictor=table_pred,
|
|
115
|
+
formula_predictor=formula_pred,
|
|
116
|
+
ignore_regions=ignore_regions,
|
|
59
117
|
**kwargs,
|
|
60
118
|
)
|
|
61
119
|
|
|
@@ -72,6 +130,12 @@ def ocr_predictor(
|
|
|
72
130
|
detect_orientation: bool = False,
|
|
73
131
|
straighten_pages: bool = False,
|
|
74
132
|
detect_language: bool = False,
|
|
133
|
+
detect_layout: bool = False,
|
|
134
|
+
layout_arch: Any = "lw_detr_s",
|
|
135
|
+
ignore_regions: list[str] | None = None,
|
|
136
|
+
detect_tables: bool = False,
|
|
137
|
+
detect_formulas: bool = False,
|
|
138
|
+
confidence_aggregation: ConfidenceAggregation | None = None,
|
|
75
139
|
**kwargs: Any,
|
|
76
140
|
) -> OCRPredictor:
|
|
77
141
|
"""End-to-end OCR architecture using one model for localization, and another for text recognition.
|
|
@@ -104,7 +168,28 @@ def ocr_predictor(
|
|
|
104
168
|
Doing so will improve performances for documents with page-uniform rotations.
|
|
105
169
|
detect_language: if True, the language prediction will be added to the predictions for each
|
|
106
170
|
page. Doing so will slightly deteriorate the overall latency.
|
|
107
|
-
|
|
171
|
+
detect_layout: if True, a layout detection model is run on each page and the detected regions are attached
|
|
172
|
+
to each page.
|
|
173
|
+
Doing so will slightly deteriorate the overall latency.
|
|
174
|
+
layout_arch: name of the layout architecture or the model itself to use.
|
|
175
|
+
ignore_regions: optional list of layout class names to ignore during detection/recognition. If provided, the
|
|
176
|
+
layout model will be used to locate the regions of the specified classes, and these regions will
|
|
177
|
+
be masked out (filled with black) before passing the pages to the detection/recognition modules.
|
|
178
|
+
detect_tables: if True, table regions found by the layout model are cropped and passed to a table
|
|
179
|
+
structure model. Words falling inside a detected table are regrouped into a structured table
|
|
180
|
+
(accessible via `page.tables`) and removed from the regular text output. This enables the layout
|
|
181
|
+
model and slightly deteriorates the overall latency.
|
|
182
|
+
detect_formulas: if True, formula regions found by the layout model are masked out of the text detection,
|
|
183
|
+
cropped and read as LaTeX by a formula recognition model (accessible via `page.formulas`, and exported as
|
|
184
|
+
display math, e.g. `$$...$$` in Markdown). This enables the layout model and deteriorates the overall
|
|
185
|
+
latency.
|
|
186
|
+
confidence_aggregation: aggregation method of the character probabilities of the recognition model into the
|
|
187
|
+
word confidence: "mean", "min", "max", "median", "geometric_mean", "harmonic_mean" or a Python callable
|
|
188
|
+
taking the 1D array of probabilities and returning a float. If None (default), the method of the
|
|
189
|
+
recognition model is kept ("min" for CRNN, VIPTR, SAR and MASTER, "mean" for ViTSTR and PARSeq).
|
|
190
|
+
A recognition model instance passed as `reco_arch` is modified.
|
|
191
|
+
kwargs: keyword args of `OCRPredictor` (e.g. `page_chunk_size`, the maximum number of pages of a lazy
|
|
192
|
+
page source processed at once)
|
|
108
193
|
|
|
109
194
|
Returns:
|
|
110
195
|
OCR predictor
|
|
@@ -121,6 +206,12 @@ def ocr_predictor(
|
|
|
121
206
|
detect_orientation=detect_orientation,
|
|
122
207
|
straighten_pages=straighten_pages,
|
|
123
208
|
detect_language=detect_language,
|
|
209
|
+
detect_layout=detect_layout,
|
|
210
|
+
layout_arch=layout_arch,
|
|
211
|
+
detect_tables=detect_tables,
|
|
212
|
+
detect_formulas=detect_formulas,
|
|
213
|
+
ignore_regions=ignore_regions,
|
|
214
|
+
confidence_aggregation=confidence_aggregation,
|
|
124
215
|
**kwargs,
|
|
125
216
|
)
|
|
126
217
|
|
|
@@ -138,8 +229,16 @@ def _kie_predictor(
|
|
|
138
229
|
detect_orientation: bool = False,
|
|
139
230
|
straighten_pages: bool = False,
|
|
140
231
|
detect_language: bool = False,
|
|
232
|
+
detect_layout: bool = False,
|
|
233
|
+
layout_arch: Any = "lw_detr_s",
|
|
234
|
+
ignore_regions: list[str] | None = None,
|
|
235
|
+
confidence_aggregation: ConfidenceAggregation | None = None,
|
|
141
236
|
**kwargs,
|
|
142
237
|
) -> KIEPredictor:
|
|
238
|
+
if confidence_aggregation is not None:
|
|
239
|
+
# Fail before building the models
|
|
240
|
+
_resolve_confidence_aggregation(confidence_aggregation)
|
|
241
|
+
|
|
143
242
|
# Detection
|
|
144
243
|
det_predictor = detection_predictor(
|
|
145
244
|
det_arch,
|
|
@@ -157,6 +256,21 @@ def _kie_predictor(
|
|
|
157
256
|
pretrained=pretrained,
|
|
158
257
|
pretrained_backbone=pretrained_backbone,
|
|
159
258
|
batch_size=reco_bs,
|
|
259
|
+
confidence_aggregation=confidence_aggregation,
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
# Layout - optional
|
|
263
|
+
layout_pred = (
|
|
264
|
+
layout_predictor(
|
|
265
|
+
layout_arch,
|
|
266
|
+
pretrained=pretrained,
|
|
267
|
+
assume_straight_pages=assume_straight_pages,
|
|
268
|
+
preserve_aspect_ratio=preserve_aspect_ratio,
|
|
269
|
+
symmetric_pad=symmetric_pad,
|
|
270
|
+
batch_size=det_bs,
|
|
271
|
+
)
|
|
272
|
+
if detect_layout
|
|
273
|
+
else None
|
|
160
274
|
)
|
|
161
275
|
|
|
162
276
|
return KIEPredictor(
|
|
@@ -168,6 +282,8 @@ def _kie_predictor(
|
|
|
168
282
|
detect_orientation=detect_orientation,
|
|
169
283
|
straighten_pages=straighten_pages,
|
|
170
284
|
detect_language=detect_language,
|
|
285
|
+
layout_predictor=layout_pred,
|
|
286
|
+
ignore_regions=ignore_regions,
|
|
171
287
|
**kwargs,
|
|
172
288
|
)
|
|
173
289
|
|
|
@@ -184,13 +300,17 @@ def kie_predictor(
|
|
|
184
300
|
detect_orientation: bool = False,
|
|
185
301
|
straighten_pages: bool = False,
|
|
186
302
|
detect_language: bool = False,
|
|
303
|
+
detect_layout: bool = False,
|
|
304
|
+
layout_arch: Any = "lw_detr_s",
|
|
305
|
+
ignore_regions: list[str] | None = None,
|
|
306
|
+
confidence_aggregation: ConfidenceAggregation | None = None,
|
|
187
307
|
**kwargs: Any,
|
|
188
308
|
) -> KIEPredictor:
|
|
189
309
|
"""End-to-end KIE architecture using one model for localization, and another for text recognition.
|
|
190
310
|
|
|
191
311
|
>>> import numpy as np
|
|
192
|
-
>>> from doctr.models import
|
|
193
|
-
>>> model =
|
|
312
|
+
>>> from doctr.models import kie_predictor
|
|
313
|
+
>>> model = kie_predictor('db_resnet50', 'crnn_vgg16_bn', pretrained=True)
|
|
194
314
|
>>> input_page = (255 * np.random.rand(600, 800, 3)).astype(np.uint8)
|
|
195
315
|
>>> out = model([input_page])
|
|
196
316
|
|
|
@@ -216,7 +336,20 @@ def kie_predictor(
|
|
|
216
336
|
Doing so will improve performances for documents with page-uniform rotations.
|
|
217
337
|
detect_language: if True, the language prediction will be added to the predictions for each
|
|
218
338
|
page. Doing so will slightly deteriorate the overall latency.
|
|
219
|
-
|
|
339
|
+
detect_layout: if True, a layout detection model is run on each page and the detected regions are attached
|
|
340
|
+
to each page.
|
|
341
|
+
Doing so will slightly deteriorate the overall latency.
|
|
342
|
+
layout_arch: name of the layout architecture or the model itself to use.
|
|
343
|
+
ignore_regions: optional list of layout class names to ignore during detection/recognition. If provided, the
|
|
344
|
+
layout model will be used to locate the regions of the specified classes, and these regions will
|
|
345
|
+
be masked out (filled with black) before passing the pages to the detection/recognition modules.
|
|
346
|
+
confidence_aggregation: aggregation method of the character probabilities of the recognition model into the
|
|
347
|
+
word confidence: "mean", "min", "max", "median", "geometric_mean", "harmonic_mean" or a Python callable
|
|
348
|
+
taking the 1D array of probabilities and returning a float. If None (default), the method of the
|
|
349
|
+
recognition model is kept ("min" for CRNN, VIPTR, SAR and MASTER, "mean" for ViTSTR and PARSeq).
|
|
350
|
+
A recognition model instance passed as `reco_arch` is modified.
|
|
351
|
+
kwargs: keyword args of `OCRPredictor` (e.g. `page_chunk_size`, the maximum number of pages of a lazy
|
|
352
|
+
page source processed at once)
|
|
220
353
|
|
|
221
354
|
Returns:
|
|
222
355
|
KIE predictor
|
|
@@ -233,5 +366,9 @@ def kie_predictor(
|
|
|
233
366
|
detect_orientation=detect_orientation,
|
|
234
367
|
straighten_pages=straighten_pages,
|
|
235
368
|
detect_language=detect_language,
|
|
369
|
+
detect_layout=detect_layout,
|
|
370
|
+
layout_arch=layout_arch,
|
|
371
|
+
ignore_regions=ignore_regions,
|
|
372
|
+
confidence_aggregation=confidence_aggregation,
|
|
236
373
|
**kwargs,
|
|
237
374
|
)
|
|
@@ -25,6 +25,9 @@ def crop_boxes(
|
|
|
25
25
|
Returns:
|
|
26
26
|
the cropped boxes
|
|
27
27
|
"""
|
|
28
|
+
boxes = boxes.copy()
|
|
29
|
+
if boxes.shape[0] == 0: # nothing to crop (e.g. an image without any text)
|
|
30
|
+
return boxes
|
|
28
31
|
is_box_rel = boxes.max() <= 1
|
|
29
32
|
is_crop_rel = max(crop_box) <= 1
|
|
30
33
|
|
|
@@ -61,6 +64,9 @@ def expand_line(line: np.ndarray, target_shape: tuple[int, int]) -> tuple[float,
|
|
|
61
64
|
return line[0]
|
|
62
65
|
# Get the line equation
|
|
63
66
|
_tmp = line[1] - line[0]
|
|
67
|
+
if not np.any(_tmp):
|
|
68
|
+
# Both points coincide (e.g. once rounded to pixels): there is no direction to extend the line in
|
|
69
|
+
return line[0, 0], line[0, 1]
|
|
64
70
|
_direction = _tmp > 0
|
|
65
71
|
_flat = _tmp == 0
|
|
66
72
|
# vertical case
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
from copy import deepcopy
|
|
7
7
|
|
|
8
|
+
import cv2
|
|
8
9
|
import numpy as np
|
|
9
10
|
import torch
|
|
10
11
|
from scipy.ndimage import gaussian_filter
|
|
@@ -14,7 +15,15 @@ from doctr.utils.geometry import rotate_abs_geoms
|
|
|
14
15
|
|
|
15
16
|
from .base import create_shadow_mask, crop_boxes
|
|
16
17
|
|
|
17
|
-
__all__ = [
|
|
18
|
+
__all__ = [
|
|
19
|
+
"invert_colors",
|
|
20
|
+
"rotate_sample",
|
|
21
|
+
"crop_detection",
|
|
22
|
+
"random_shadow",
|
|
23
|
+
"random_glare",
|
|
24
|
+
"random_lighting",
|
|
25
|
+
"perspective_sample",
|
|
26
|
+
]
|
|
18
27
|
|
|
19
28
|
|
|
20
29
|
def invert_colors(img: torch.Tensor, min_val: float = 0.6) -> torch.Tensor:
|
|
@@ -62,12 +71,14 @@ def rotate_sample(
|
|
|
62
71
|
rotated_img = rotated_img[:3] # when expand=True, it expands to RGBA channels
|
|
63
72
|
# Get absolute coords
|
|
64
73
|
_geoms = deepcopy(geoms)
|
|
74
|
+
# Relative coordinates are scaled to the image size (an empty array has no coordinates to scale)
|
|
75
|
+
is_relative = _geoms.size == 0 or np.max(_geoms) <= 1
|
|
65
76
|
if _geoms.shape[1:] == (4,):
|
|
66
|
-
if
|
|
77
|
+
if is_relative:
|
|
67
78
|
_geoms[:, [0, 2]] *= img.shape[-1]
|
|
68
79
|
_geoms[:, [1, 3]] *= img.shape[-2]
|
|
69
80
|
elif _geoms.shape[1:] == (4, 2):
|
|
70
|
-
if
|
|
81
|
+
if is_relative:
|
|
71
82
|
_geoms[..., 0] *= img.shape[-1]
|
|
72
83
|
_geoms[..., 1] *= img.shape[-2]
|
|
73
84
|
else:
|
|
@@ -104,11 +115,11 @@ def crop_detection(
|
|
|
104
115
|
if any(val < 0 or val > 1 for val in crop_box):
|
|
105
116
|
raise AssertionError("coordinates of arg `crop_box` should be relative")
|
|
106
117
|
h, w = img.shape[-2:]
|
|
107
|
-
xmin, ymin = int(round(crop_box[0] *
|
|
108
|
-
xmax, ymax = int(round(crop_box[2] *
|
|
118
|
+
xmin, ymin = int(round(crop_box[0] * w)), int(round(crop_box[1] * h))
|
|
119
|
+
xmax, ymax = int(round(crop_box[2] * w)), int(round(crop_box[3] * h))
|
|
109
120
|
cropped_img = F.crop(img, ymin, xmin, ymax - ymin, xmax - xmin)
|
|
110
121
|
# Crop the box
|
|
111
|
-
boxes = crop_boxes(boxes, crop_box if boxes.max() <= 1 else (xmin, ymin, xmax, ymax))
|
|
122
|
+
boxes = crop_boxes(boxes, crop_box if boxes.size == 0 or boxes.max() <= 1 else (xmin, ymin, xmax, ymax))
|
|
112
123
|
|
|
113
124
|
return cropped_img, boxes
|
|
114
125
|
|
|
@@ -135,3 +146,120 @@ def random_shadow(img: torch.Tensor, opacity_range: tuple[float, float], **kwarg
|
|
|
135
146
|
shadow_tensor = shadow_tensor.to(img.device).unsqueeze(0) # Add channel dimension
|
|
136
147
|
|
|
137
148
|
return opacity * shadow_tensor * img + (1 - opacity) * img
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def random_glare(
|
|
152
|
+
img: torch.Tensor, opacity_range: tuple[float, float], num_spots: tuple[int, int] = (1, 3)
|
|
153
|
+
) -> torch.Tensor:
|
|
154
|
+
"""Add soft bright spots, like the specular reflections of a light source on a photographed screen or a glossy
|
|
155
|
+
sheet.
|
|
156
|
+
|
|
157
|
+
Args:
|
|
158
|
+
img: image to modify (C, H, W), float in [0, 1]
|
|
159
|
+
opacity_range: minimum and maximum strength of the reflections
|
|
160
|
+
num_spots: minimum and maximum number of reflections
|
|
161
|
+
|
|
162
|
+
Returns:
|
|
163
|
+
the image with the reflections blended towards white (same shape as input)
|
|
164
|
+
"""
|
|
165
|
+
_, h, w = img.shape
|
|
166
|
+
ys, xs = np.mgrid[0:h, 0:w].astype(np.float32)
|
|
167
|
+
mask = np.zeros((h, w), dtype=np.float32)
|
|
168
|
+
for _ in range(np.random.randint(num_spots[0], num_spots[1] + 1)):
|
|
169
|
+
cx, cy = np.random.uniform(0, w), np.random.uniform(0, h)
|
|
170
|
+
rx, ry = np.random.uniform(0.08, 0.35) * w, np.random.uniform(0.08, 0.35) * h
|
|
171
|
+
theta = np.random.uniform(0, np.pi)
|
|
172
|
+
dx, dy = xs - cx, ys - cy
|
|
173
|
+
u = dx * np.cos(theta) + dy * np.sin(theta)
|
|
174
|
+
v = -dx * np.sin(theta) + dy * np.cos(theta)
|
|
175
|
+
mask = np.maximum(mask, np.exp(-((u / rx) ** 2 + (v / ry) ** 2)))
|
|
176
|
+
opacity = float(np.random.uniform(*opacity_range))
|
|
177
|
+
glare = torch.from_numpy(mask).to(device=img.device, dtype=img.dtype).unsqueeze(0) * opacity
|
|
178
|
+
return img + glare * (1 - img)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def random_lighting(
|
|
182
|
+
img: torch.Tensor, strength_range: tuple[float, float], grid: tuple[int, int] = (2, 4)
|
|
183
|
+
) -> torch.Tensor:
|
|
184
|
+
"""Multiply the image by a smooth, low-frequency brightness field: uneven lighting, the shading of a crumpled
|
|
185
|
+
or curved sheet, vignetting.
|
|
186
|
+
|
|
187
|
+
Args:
|
|
188
|
+
img: image to modify (C, H, W), float in [0, 1]
|
|
189
|
+
strength_range: minimum and maximum amplitude of the field (0.3 = brightness between 0.7 and 1.3)
|
|
190
|
+
grid: minimum and maximum size of the random grid that is upsampled into the field
|
|
191
|
+
|
|
192
|
+
Returns:
|
|
193
|
+
the modulated image (same shape as input)
|
|
194
|
+
"""
|
|
195
|
+
_, h, w = img.shape
|
|
196
|
+
n = np.random.randint(grid[0], grid[1] + 1)
|
|
197
|
+
strength = np.random.uniform(*strength_range)
|
|
198
|
+
coarse = np.random.uniform(-1, 1, size=(n, n)).astype(np.float32)
|
|
199
|
+
field = cv2.resize(coarse, (w, h), interpolation=cv2.INTER_CUBIC)
|
|
200
|
+
field = (1 + strength * np.clip(field, -1, 1)).astype(np.float32)
|
|
201
|
+
return (img * torch.from_numpy(field).to(device=img.device, dtype=img.dtype).unsqueeze(0)).clamp(0, 1)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def perspective_sample(
|
|
205
|
+
img: torch.Tensor,
|
|
206
|
+
geoms: np.ndarray,
|
|
207
|
+
distortion: float,
|
|
208
|
+
mask: torch.Tensor | None = None,
|
|
209
|
+
) -> tuple[torch.Tensor, np.ndarray, torch.Tensor | None]:
|
|
210
|
+
"""Warp an image (and its boxes / polygons) with a random perspective, as if it were photographed at an angle.
|
|
211
|
+
|
|
212
|
+
The four corners of the image are moved inwards by up to `distortion` times the image size, and the image is
|
|
213
|
+
warped so that the original corners land on the moved ones (the content shrinks, the borders are filled with
|
|
214
|
+
zeros like a background around a photographed page).
|
|
215
|
+
|
|
216
|
+
Args:
|
|
217
|
+
img: image to warp (C, H, W)
|
|
218
|
+
geoms: relative boxes (N, 4) or polygons (N, 4, 2) in [0, 1]
|
|
219
|
+
distortion: maximum relative displacement of every corner
|
|
220
|
+
mask: optional (H, W) boolean validity mask warped alongside
|
|
221
|
+
|
|
222
|
+
Returns:
|
|
223
|
+
the warped image, the warped geometries (same format, clipped to [0, 1]) and the warped mask
|
|
224
|
+
"""
|
|
225
|
+
_, h, w = img.shape
|
|
226
|
+
start = np.array([[0, 0], [w - 1, 0], [w - 1, h - 1], [0, h - 1]], dtype=np.float32)
|
|
227
|
+
dx, dy = distortion * w, distortion * h
|
|
228
|
+
end = start + np.array(
|
|
229
|
+
[
|
|
230
|
+
[np.random.uniform(0, dx), np.random.uniform(0, dy)],
|
|
231
|
+
[-np.random.uniform(0, dx), np.random.uniform(0, dy)],
|
|
232
|
+
[-np.random.uniform(0, dx), -np.random.uniform(0, dy)],
|
|
233
|
+
[np.random.uniform(0, dx), -np.random.uniform(0, dy)],
|
|
234
|
+
],
|
|
235
|
+
dtype=np.float32,
|
|
236
|
+
)
|
|
237
|
+
warped = F.perspective(img, start.tolist(), end.tolist(), interpolation=F.InterpolationMode.BILINEAR, fill=0)
|
|
238
|
+
warped_mask = None
|
|
239
|
+
if mask is not None:
|
|
240
|
+
warped_mask = (
|
|
241
|
+
F
|
|
242
|
+
.perspective(
|
|
243
|
+
mask.unsqueeze(0).to(torch.uint8), start.tolist(), end.tolist(), F.InterpolationMode.NEAREST, fill=0
|
|
244
|
+
)
|
|
245
|
+
.squeeze(0)
|
|
246
|
+
.to(torch.bool)
|
|
247
|
+
)
|
|
248
|
+
if geoms.shape[0] == 0:
|
|
249
|
+
return warped, geoms.copy(), warped_mask
|
|
250
|
+
|
|
251
|
+
matrix = cv2.getPerspectiveTransform(start, end)
|
|
252
|
+
is_polygon = geoms.ndim == 3
|
|
253
|
+
if is_polygon:
|
|
254
|
+
pts = geoms.astype(np.float32).reshape(-1, 4, 2)
|
|
255
|
+
else:
|
|
256
|
+
x1, y1, x2, y2 = (geoms[:, i].astype(np.float32) for i in range(4))
|
|
257
|
+
pts = np.stack([np.stack([x1, y1], 1), np.stack([x2, y1], 1), np.stack([x2, y2], 1), np.stack([x1, y2], 1)], 1)
|
|
258
|
+
abs_pts = pts * np.array([w, h], dtype=np.float32)
|
|
259
|
+
out = cv2.perspectiveTransform(abs_pts.reshape(-1, 1, 2), matrix).reshape(-1, 4, 2)
|
|
260
|
+
rel = out / np.array([w, h], dtype=np.float32)
|
|
261
|
+
rel = np.clip(rel, 0, 1)
|
|
262
|
+
if is_polygon:
|
|
263
|
+
return warped, rel.astype(geoms.dtype), warped_mask
|
|
264
|
+
boxes = np.concatenate([rel.min(axis=1), rel.max(axis=1)], axis=1).astype(geoms.dtype)
|
|
265
|
+
return warped, boxes, warped_mask
|