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
|
@@ -4,16 +4,18 @@
|
|
|
4
4
|
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
|
|
5
5
|
|
|
6
6
|
import math
|
|
7
|
+
from collections.abc import Sequence
|
|
7
8
|
|
|
8
9
|
import numpy as np
|
|
9
10
|
import torch
|
|
10
|
-
from PIL.Image import Image
|
|
11
11
|
from scipy.ndimage import gaussian_filter
|
|
12
12
|
from torch.nn.functional import pad
|
|
13
13
|
from torchvision.transforms import functional as F
|
|
14
14
|
from torchvision.transforms import transforms as T
|
|
15
15
|
|
|
16
|
-
from
|
|
16
|
+
from doctr.utils import Sample
|
|
17
|
+
|
|
18
|
+
from ..functional import perspective_sample, random_glare, random_lighting, random_shadow
|
|
17
19
|
|
|
18
20
|
__all__ = [
|
|
19
21
|
"Resize",
|
|
@@ -22,7 +24,11 @@ __all__ = [
|
|
|
22
24
|
"RandomHorizontalFlip",
|
|
23
25
|
"RandomShadow",
|
|
24
26
|
"RandomResize",
|
|
27
|
+
"RandomPad",
|
|
25
28
|
"GaussianBlur",
|
|
29
|
+
"RandomGlare",
|
|
30
|
+
"RandomLighting",
|
|
31
|
+
"RandomPerspective",
|
|
26
32
|
]
|
|
27
33
|
|
|
28
34
|
|
|
@@ -31,8 +37,9 @@ class Resize(T.Resize):
|
|
|
31
37
|
|
|
32
38
|
>>> import torch
|
|
33
39
|
>>> from doctr.transforms import Resize
|
|
40
|
+
>>> from doctr.utils import Sample
|
|
34
41
|
>>> transfo = Resize((64, 64), preserve_aspect_ratio=True, symmetric_pad=True)
|
|
35
|
-
>>> out = transfo(torch.rand((3, 64, 64)))
|
|
42
|
+
>>> out = transfo(Sample(image=torch.rand((3, 64, 64))))
|
|
36
43
|
|
|
37
44
|
Args:
|
|
38
45
|
size: output size in pixels, either a tuple (height, width) or a single integer for square images
|
|
@@ -41,6 +48,9 @@ class Resize(T.Resize):
|
|
|
41
48
|
if True, the image will be resized to fit within the target size while maintaining its aspect ratio
|
|
42
49
|
symmetric_pad: whether to symmetrically pad the image to the target size,
|
|
43
50
|
if True, the image will be padded equally on both sides to fit the target size
|
|
51
|
+
return_padding_mask: whether to return a boolean mask alongside the image, with True on valid
|
|
52
|
+
(image content) pixels and False on padded areas. This matches how masks propagate through the
|
|
53
|
+
other transforms (padding and rotation fill new areas with False).
|
|
44
54
|
"""
|
|
45
55
|
|
|
46
56
|
def __init__(
|
|
@@ -49,25 +59,87 @@ class Resize(T.Resize):
|
|
|
49
59
|
interpolation=F.InterpolationMode.BILINEAR,
|
|
50
60
|
preserve_aspect_ratio: bool = False,
|
|
51
61
|
symmetric_pad: bool = False,
|
|
62
|
+
return_padding_mask: bool = False,
|
|
52
63
|
) -> None:
|
|
53
64
|
super().__init__(size if isinstance(size, (list, tuple)) else (size, size), interpolation, antialias=True)
|
|
54
65
|
self.preserve_aspect_ratio = preserve_aspect_ratio
|
|
55
66
|
self.symmetric_pad = symmetric_pad
|
|
67
|
+
self.return_padding_mask = return_padding_mask
|
|
68
|
+
|
|
69
|
+
def _resize_target(
|
|
70
|
+
self,
|
|
71
|
+
target: np.ndarray,
|
|
72
|
+
raw_shape: Sequence[int],
|
|
73
|
+
final_shape: Sequence[int],
|
|
74
|
+
symmetric_pad: bool = False,
|
|
75
|
+
offset: tuple[int, int] = (0, 0),
|
|
76
|
+
) -> np.ndarray:
|
|
77
|
+
"""Resize the target boxes according to the resizing of the image and the padding if needed"""
|
|
78
|
+
target = target.copy()
|
|
79
|
+
|
|
80
|
+
if target.shape[1:] == (4,):
|
|
81
|
+
if symmetric_pad:
|
|
82
|
+
target[:, [0, 2]] = offset[0] + target[:, [0, 2]] * raw_shape[-1] / final_shape[-1]
|
|
83
|
+
target[:, [1, 3]] = offset[1] + target[:, [1, 3]] * raw_shape[-2] / final_shape[-2]
|
|
84
|
+
else:
|
|
85
|
+
target[:, [0, 2]] *= raw_shape[-1] / final_shape[-1]
|
|
86
|
+
target[:, [1, 3]] *= raw_shape[-2] / final_shape[-2]
|
|
87
|
+
|
|
88
|
+
elif target.shape[1:] == (4, 2):
|
|
89
|
+
if symmetric_pad:
|
|
90
|
+
target[..., 0] = offset[0] + target[..., 0] * raw_shape[-1] / final_shape[-1]
|
|
91
|
+
target[..., 1] = offset[1] + target[..., 1] * raw_shape[-2] / final_shape[-2]
|
|
92
|
+
else:
|
|
93
|
+
target[..., 0] *= raw_shape[-1] / final_shape[-1]
|
|
94
|
+
target[..., 1] *= raw_shape[-2] / final_shape[-2]
|
|
95
|
+
|
|
96
|
+
else:
|
|
97
|
+
raise AssertionError("Boxes should be in the format (n_boxes, 4, 2) or (n_boxes, 4)")
|
|
98
|
+
|
|
99
|
+
return np.clip(target, 0, 1)
|
|
56
100
|
|
|
57
101
|
def forward(
|
|
58
102
|
self,
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
103
|
+
sample: Sample,
|
|
104
|
+
) -> Sample:
|
|
105
|
+
img = sample.image
|
|
106
|
+
target = sample.target
|
|
107
|
+
mask = sample.mask
|
|
108
|
+
|
|
109
|
+
# Resize mask alongside image if provided
|
|
110
|
+
# Masks should use nearest interpolation to preserve label integrity
|
|
111
|
+
resize_mask = mask is not None
|
|
112
|
+
if resize_mask and mask is not None and mask.ndim == 2:
|
|
113
|
+
mask = mask.unsqueeze(0)
|
|
114
|
+
|
|
62
115
|
target_ratio = self.size[0] / self.size[1]
|
|
63
116
|
actual_ratio = img.shape[-2] / img.shape[-1]
|
|
64
117
|
|
|
65
118
|
if not self.preserve_aspect_ratio or (target_ratio == actual_ratio):
|
|
66
119
|
# If we don't preserve the aspect ratio or the wanted aspect ratio is the same than the original one
|
|
67
120
|
# We can use with the regular resize
|
|
121
|
+
img = super().forward(img)
|
|
122
|
+
|
|
123
|
+
if resize_mask:
|
|
124
|
+
mask = F.resize(
|
|
125
|
+
mask,
|
|
126
|
+
self.size,
|
|
127
|
+
interpolation=F.InterpolationMode.NEAREST,
|
|
128
|
+
antialias=False,
|
|
129
|
+
).squeeze(0)
|
|
130
|
+
|
|
131
|
+
if self.return_padding_mask:
|
|
132
|
+
# No padding was added: every pixel is valid image content
|
|
133
|
+
padding_mask = torch.ones(self.size, dtype=torch.bool, device=img.device)
|
|
134
|
+
|
|
68
135
|
if target is not None:
|
|
69
|
-
|
|
70
|
-
|
|
136
|
+
if self.return_padding_mask:
|
|
137
|
+
return sample.replace(image=img, target=target, mask=mask if resize_mask else padding_mask)
|
|
138
|
+
return sample.replace(image=img, target=target, mask=mask if resize_mask else sample.mask)
|
|
139
|
+
if self.return_padding_mask:
|
|
140
|
+
return sample.replace(image=img, mask=mask if resize_mask else padding_mask)
|
|
141
|
+
return sample.replace(image=img, mask=mask if resize_mask else sample.mask)
|
|
142
|
+
|
|
71
143
|
else:
|
|
72
144
|
# Resize
|
|
73
145
|
if actual_ratio > target_ratio:
|
|
@@ -77,43 +149,77 @@ class Resize(T.Resize):
|
|
|
77
149
|
|
|
78
150
|
# Scale image
|
|
79
151
|
img = F.resize(img, tmp_size, self.interpolation, antialias=True)
|
|
152
|
+
|
|
153
|
+
if resize_mask:
|
|
154
|
+
mask = F.resize(
|
|
155
|
+
mask,
|
|
156
|
+
tmp_size,
|
|
157
|
+
interpolation=F.InterpolationMode.NEAREST,
|
|
158
|
+
antialias=False,
|
|
159
|
+
).squeeze(0)
|
|
160
|
+
|
|
80
161
|
raw_shape = img.shape[-2:]
|
|
162
|
+
|
|
81
163
|
if isinstance(self.size, (tuple, list)):
|
|
82
164
|
# Pad (inverted in pytorch)
|
|
83
165
|
_pad = (0, self.size[1] - img.shape[-1], 0, self.size[0] - img.shape[-2])
|
|
166
|
+
|
|
84
167
|
if self.symmetric_pad:
|
|
85
168
|
half_pad = (math.ceil(_pad[1] / 2), math.ceil(_pad[3] / 2))
|
|
86
169
|
_pad = (half_pad[0], _pad[1] - half_pad[0], half_pad[1], _pad[3] - half_pad[1])
|
|
87
170
|
# Pad image
|
|
88
171
|
img = pad(img, _pad)
|
|
89
172
|
|
|
173
|
+
if resize_mask and mask is not None:
|
|
174
|
+
mask = pad(mask, _pad)
|
|
175
|
+
|
|
176
|
+
if self.return_padding_mask:
|
|
177
|
+
# True on valid (image content) pixels, False on the padded borders
|
|
178
|
+
h, w = self.size
|
|
179
|
+
padding_mask = torch.zeros((h, w), dtype=torch.bool, device=img.device)
|
|
180
|
+
left, right, top, bottom = _pad
|
|
181
|
+
padding_mask[top : h - bottom, left : w - right] = True
|
|
182
|
+
|
|
90
183
|
# In case boxes are provided, resize boxes if needed (for detection task if preserve aspect ratio)
|
|
91
184
|
if target is not None:
|
|
92
185
|
if self.symmetric_pad:
|
|
93
|
-
offset =
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
186
|
+
offset = (
|
|
187
|
+
half_pad[0] / img.shape[-1],
|
|
188
|
+
half_pad[1] / img.shape[-2],
|
|
189
|
+
)
|
|
190
|
+
else:
|
|
191
|
+
offset = (0, 0)
|
|
192
|
+
|
|
193
|
+
if isinstance(target, str) or (isinstance(target, np.ndarray) and target.shape == (1,)):
|
|
194
|
+
# Special case for orientation targets and other non-box targets, which should not be resized
|
|
195
|
+
pass
|
|
196
|
+
elif isinstance(target, dict):
|
|
197
|
+
target = {
|
|
198
|
+
cls_name: self._resize_target(
|
|
199
|
+
arr,
|
|
200
|
+
raw_shape,
|
|
201
|
+
img.shape[-2:],
|
|
202
|
+
symmetric_pad=self.symmetric_pad,
|
|
203
|
+
offset=offset,
|
|
204
|
+
)
|
|
205
|
+
for cls_name, arr in target.items()
|
|
206
|
+
}
|
|
207
|
+
else:
|
|
208
|
+
target = self._resize_target(
|
|
209
|
+
target,
|
|
210
|
+
raw_shape,
|
|
211
|
+
img.shape[-2:],
|
|
212
|
+
symmetric_pad=self.symmetric_pad,
|
|
213
|
+
offset=offset,
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
if target is not None:
|
|
217
|
+
if self.return_padding_mask:
|
|
218
|
+
return sample.replace(image=img, target=target, mask=mask if resize_mask else padding_mask)
|
|
219
|
+
return sample.replace(image=img, target=target, mask=mask if resize_mask else sample.mask)
|
|
220
|
+
if self.return_padding_mask:
|
|
221
|
+
return sample.replace(image=img, mask=mask if resize_mask else padding_mask)
|
|
222
|
+
return sample.replace(image=img, mask=mask if resize_mask else sample.mask)
|
|
117
223
|
|
|
118
224
|
def __repr__(self) -> str:
|
|
119
225
|
interpolate_str = self.interpolation.value
|
|
@@ -128,8 +234,9 @@ class GaussianNoise(torch.nn.Module):
|
|
|
128
234
|
|
|
129
235
|
>>> import torch
|
|
130
236
|
>>> from doctr.transforms import GaussianNoise
|
|
237
|
+
>>> from doctr.utils import Sample
|
|
131
238
|
>>> transfo = GaussianNoise(0., 1.)
|
|
132
|
-
>>> out = transfo(torch.rand((3, 224, 224)))
|
|
239
|
+
>>> out = transfo(Sample(image=torch.rand((3, 224, 224))))
|
|
133
240
|
|
|
134
241
|
Args:
|
|
135
242
|
mean : mean of the gaussian distribution
|
|
@@ -141,13 +248,14 @@ class GaussianNoise(torch.nn.Module):
|
|
|
141
248
|
self.std = std
|
|
142
249
|
self.mean = mean
|
|
143
250
|
|
|
144
|
-
def forward(self,
|
|
145
|
-
|
|
251
|
+
def forward(self, sample: Sample) -> Sample:
|
|
252
|
+
x = sample.image
|
|
146
253
|
noise = self.mean + 2 * self.std * torch.rand(x.shape, device=x.device) - self.std
|
|
147
254
|
if x.dtype == torch.uint8:
|
|
148
|
-
|
|
255
|
+
image = (x + 255 * noise).round().clamp(0, 255).to(dtype=torch.uint8)
|
|
149
256
|
else:
|
|
150
|
-
|
|
257
|
+
image = (x + noise.to(dtype=x.dtype)).clamp(0, 1)
|
|
258
|
+
return sample.replace(image=image)
|
|
151
259
|
|
|
152
260
|
def extra_repr(self) -> str:
|
|
153
261
|
return f"mean={self.mean}, std={self.std}"
|
|
@@ -158,7 +266,9 @@ class GaussianBlur(torch.nn.Module):
|
|
|
158
266
|
|
|
159
267
|
>>> import torch
|
|
160
268
|
>>> from doctr.transforms import GaussianBlur
|
|
269
|
+
>>> from doctr.utils import Sample
|
|
161
270
|
>>> transfo = GaussianBlur(sigma=(0.0, 1.0))
|
|
271
|
+
>>> out = transfo(Sample(image=torch.rand((3, 224, 224))))
|
|
162
272
|
|
|
163
273
|
Args:
|
|
164
274
|
sigma : standard deviation range for the gaussian kernel
|
|
@@ -168,50 +278,77 @@ class GaussianBlur(torch.nn.Module):
|
|
|
168
278
|
super().__init__()
|
|
169
279
|
self.sigma_range = sigma
|
|
170
280
|
|
|
171
|
-
def forward(self,
|
|
281
|
+
def forward(self, sample: Sample) -> Sample:
|
|
172
282
|
# Sample a random sigma value within the specified range
|
|
173
283
|
sigma = torch.empty(1).uniform_(*self.sigma_range).item()
|
|
174
284
|
|
|
175
|
-
# Apply Gaussian blur along spatial dimensions only
|
|
285
|
+
# Apply Gaussian blur along spatial dimensions only (a zero sigma leaves the leading channel axis untouched)
|
|
176
286
|
blurred = torch.tensor(
|
|
177
287
|
gaussian_filter(
|
|
178
|
-
|
|
179
|
-
sigma=sigma,
|
|
288
|
+
sample.image.numpy(),
|
|
289
|
+
sigma=(0.0,) * (sample.image.ndim - 2) + (sigma, sigma),
|
|
180
290
|
mode="reflect",
|
|
181
291
|
truncate=4.0,
|
|
182
292
|
),
|
|
183
|
-
dtype=
|
|
184
|
-
device=
|
|
293
|
+
dtype=sample.image.dtype,
|
|
294
|
+
device=sample.image.device,
|
|
185
295
|
)
|
|
186
|
-
return blurred
|
|
296
|
+
return sample.replace(image=blurred)
|
|
187
297
|
|
|
188
298
|
|
|
189
299
|
class ChannelShuffle(torch.nn.Module):
|
|
190
|
-
"""Randomly shuffle channel order of a given image
|
|
300
|
+
"""Randomly shuffle channel order of a given image
|
|
301
|
+
|
|
302
|
+
>>> import torch
|
|
303
|
+
>>> from doctr.transforms import ChannelShuffle
|
|
304
|
+
>>> from doctr.utils import Sample
|
|
305
|
+
>>> transfo = ChannelShuffle()
|
|
306
|
+
>>> out = transfo(Sample(image=torch.rand((3, 224, 224))))
|
|
307
|
+
"""
|
|
191
308
|
|
|
192
309
|
def __init__(self):
|
|
193
310
|
super().__init__()
|
|
194
311
|
|
|
195
|
-
def forward(self,
|
|
312
|
+
def forward(self, sample: Sample) -> Sample:
|
|
196
313
|
# Get a random order
|
|
197
|
-
chan_order = torch.rand(
|
|
198
|
-
return
|
|
314
|
+
chan_order = torch.rand(sample.image.shape[0]).argsort()
|
|
315
|
+
return sample.replace(image=sample.image[chan_order])
|
|
199
316
|
|
|
200
317
|
|
|
201
318
|
class RandomHorizontalFlip(T.RandomHorizontalFlip):
|
|
202
|
-
"""Randomly flip the input image horizontally
|
|
319
|
+
"""Randomly flip the input image horizontally
|
|
320
|
+
|
|
321
|
+
>>> import torch
|
|
322
|
+
>>> from doctr.transforms import RandomHorizontalFlip
|
|
323
|
+
>>> from doctr.utils import Sample
|
|
324
|
+
>>> transfo = RandomHorizontalFlip(p=1.0)
|
|
325
|
+
>>> out = transfo(Sample(image=torch.rand((3, 224, 224)), target=np.array([[0.1, 0.2, 0.3, 0.4]])))
|
|
326
|
+
"""
|
|
327
|
+
|
|
328
|
+
def _flip_array(self, target):
|
|
329
|
+
_target = target.copy()
|
|
330
|
+
# Changing the relative bbox coordinates
|
|
331
|
+
if target.shape[1:] == (4,):
|
|
332
|
+
_target[:, ::2] = 1 - target[:, [2, 0]]
|
|
333
|
+
else:
|
|
334
|
+
_target[..., 0] = 1 - target[..., 0]
|
|
335
|
+
return _target
|
|
203
336
|
|
|
204
|
-
def forward(self,
|
|
337
|
+
def forward(self, sample: Sample) -> Sample:
|
|
205
338
|
if torch.rand(1) < self.p:
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
339
|
+
img = F.hflip(sample.image)
|
|
340
|
+
mask = F.hflip(sample.mask) if sample.mask is not None else None
|
|
341
|
+
|
|
342
|
+
target = sample.target
|
|
343
|
+
if target is not None:
|
|
344
|
+
if isinstance(target, dict):
|
|
345
|
+
target = {k: self._flip_array(v) for k, v in target.items()}
|
|
346
|
+
else:
|
|
347
|
+
target = self._flip_array(target)
|
|
348
|
+
|
|
349
|
+
return sample.replace(image=img, mask=mask, target=target)
|
|
350
|
+
|
|
351
|
+
return sample
|
|
215
352
|
|
|
216
353
|
|
|
217
354
|
class RandomShadow(torch.nn.Module):
|
|
@@ -219,8 +356,9 @@ class RandomShadow(torch.nn.Module):
|
|
|
219
356
|
|
|
220
357
|
>>> import torch
|
|
221
358
|
>>> from doctr.transforms import RandomShadow
|
|
359
|
+
>>> from doctr.utils import Sample
|
|
222
360
|
>>> transfo = RandomShadow((0., 1.))
|
|
223
|
-
>>> out = transfo(torch.rand((3, 64, 64)))
|
|
361
|
+
>>> out = transfo(Sample(image=torch.rand((3, 64, 64))))
|
|
224
362
|
|
|
225
363
|
Args:
|
|
226
364
|
opacity_range : minimum and maximum opacity of the shade
|
|
@@ -230,15 +368,15 @@ class RandomShadow(torch.nn.Module):
|
|
|
230
368
|
super().__init__()
|
|
231
369
|
self.opacity_range = opacity_range if isinstance(opacity_range, tuple) else (0.2, 0.8)
|
|
232
370
|
|
|
233
|
-
def __call__(self,
|
|
371
|
+
def __call__(self, sample: Sample) -> Sample:
|
|
234
372
|
# Reshape the distribution
|
|
235
373
|
try:
|
|
236
|
-
if
|
|
237
|
-
|
|
374
|
+
if sample.image.dtype == torch.uint8:
|
|
375
|
+
shadowed_image = (
|
|
238
376
|
(
|
|
239
377
|
255
|
|
240
378
|
* random_shadow(
|
|
241
|
-
|
|
379
|
+
sample.image.to(dtype=torch.float32) / 255,
|
|
242
380
|
self.opacity_range,
|
|
243
381
|
)
|
|
244
382
|
)
|
|
@@ -246,10 +384,12 @@ class RandomShadow(torch.nn.Module):
|
|
|
246
384
|
.clip(0, 255)
|
|
247
385
|
.to(dtype=torch.uint8)
|
|
248
386
|
)
|
|
387
|
+
return sample.replace(image=shadowed_image)
|
|
249
388
|
else:
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
389
|
+
shadowed_image = random_shadow(sample.image, self.opacity_range).clip(0, 1)
|
|
390
|
+
return sample.replace(image=shadowed_image)
|
|
391
|
+
except ValueError: # pragma: no cover
|
|
392
|
+
return sample
|
|
253
393
|
|
|
254
394
|
def extra_repr(self) -> str:
|
|
255
395
|
return f"opacity_range={self.opacity_range}"
|
|
@@ -260,8 +400,9 @@ class RandomResize(torch.nn.Module):
|
|
|
260
400
|
|
|
261
401
|
>>> import torch
|
|
262
402
|
>>> from doctr.transforms import RandomResize
|
|
403
|
+
>>> from doctr.utils import Sample
|
|
263
404
|
>>> transfo = RandomResize((0.3, 0.9), preserve_aspect_ratio=True, symmetric_pad=True, p=0.5)
|
|
264
|
-
>>> out = transfo(torch.rand((3, 64, 64)))
|
|
405
|
+
>>> out = transfo(Sample(image=torch.rand((3, 64, 64))))
|
|
265
406
|
|
|
266
407
|
Args:
|
|
267
408
|
scale_range: range of the resizing factor for width and height (independently)
|
|
@@ -286,24 +427,203 @@ class RandomResize(torch.nn.Module):
|
|
|
286
427
|
self.p = p
|
|
287
428
|
self._resize = Resize
|
|
288
429
|
|
|
289
|
-
def forward(
|
|
430
|
+
def forward(
|
|
431
|
+
self,
|
|
432
|
+
sample: Sample,
|
|
433
|
+
) -> Sample:
|
|
290
434
|
if torch.rand(1) < self.p:
|
|
291
435
|
scale_h = np.random.uniform(*self.scale_range)
|
|
292
436
|
scale_w = np.random.uniform(*self.scale_range)
|
|
293
|
-
|
|
437
|
+
# A side scaled below one pixel is kept at one pixel, as an image can not be resized to zero pixels
|
|
438
|
+
new_size = (
|
|
439
|
+
max(1, int(sample.image.shape[-2] * scale_h)),
|
|
440
|
+
max(1, int(sample.image.shape[-1] * scale_w)),
|
|
441
|
+
)
|
|
294
442
|
|
|
295
|
-
|
|
443
|
+
res = self._resize(
|
|
296
444
|
new_size,
|
|
297
445
|
preserve_aspect_ratio=self.preserve_aspect_ratio
|
|
298
446
|
if isinstance(self.preserve_aspect_ratio, bool)
|
|
299
|
-
else bool(torch.rand(1) <= self.
|
|
447
|
+
else bool(torch.rand(1) <= self.preserve_aspect_ratio),
|
|
300
448
|
symmetric_pad=self.symmetric_pad
|
|
301
449
|
if isinstance(self.symmetric_pad, bool)
|
|
302
450
|
else bool(torch.rand(1) <= self.symmetric_pad),
|
|
303
|
-
)(
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
return img, target
|
|
451
|
+
)(sample)
|
|
452
|
+
return res
|
|
453
|
+
return sample
|
|
307
454
|
|
|
308
455
|
def extra_repr(self) -> str:
|
|
309
456
|
return f"scale_range={self.scale_range}, preserve_aspect_ratio={self.preserve_aspect_ratio}, symmetric_pad={self.symmetric_pad}, p={self.p}" # noqa: E501
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
class RandomPad(torch.nn.Module):
|
|
460
|
+
"""Randomly pad the input image with its background color and align the corresponding targets
|
|
461
|
+
|
|
462
|
+
Each side gets an independent padding, filled with the background color of the image (the median color of its
|
|
463
|
+
border pixels: white for a rendered document, the paper color for a photo). Used for instance to teach a model to
|
|
464
|
+
read the crops of layout regions with their margins.
|
|
465
|
+
|
|
466
|
+
>>> import torch
|
|
467
|
+
>>> from doctr.transforms import RandomPad
|
|
468
|
+
>>> from doctr.utils import Sample
|
|
469
|
+
>>> transfo = RandomPad(max_ratio=0.5, p=0.5)
|
|
470
|
+
>>> out = transfo(Sample(image=torch.rand((3, 64, 256))))
|
|
471
|
+
|
|
472
|
+
Args:
|
|
473
|
+
max_ratio: maximum padding of each side, relative to the image height
|
|
474
|
+
p: probability to apply the transformation
|
|
475
|
+
"""
|
|
476
|
+
|
|
477
|
+
def __init__(self, max_ratio: float = 0.5, p: float = 0.5) -> None:
|
|
478
|
+
super().__init__()
|
|
479
|
+
if max_ratio < 0:
|
|
480
|
+
raise ValueError("`max_ratio` must be non-negative")
|
|
481
|
+
self.max_ratio = max_ratio
|
|
482
|
+
self.p = p
|
|
483
|
+
|
|
484
|
+
@staticmethod
|
|
485
|
+
def _pad_target(target: np.ndarray, offset: tuple[int, int], size: tuple[int, int], new_size: tuple[int, int]):
|
|
486
|
+
"""Map relative boxes (N, 4) or polygons (N, 4, 2) of the image to the padded image"""
|
|
487
|
+
if not ((target.ndim == 2 and target.shape[1] == 4) or (target.ndim == 3 and target.shape[1:] == (4, 2))):
|
|
488
|
+
raise ValueError(f"expected relative boxes (N, 4) or polygons (N, 4, 2), got shape {target.shape}")
|
|
489
|
+
(left, top), (h, w), (new_h, new_w) = offset, size, new_size
|
|
490
|
+
out = target.astype(np.float32, copy=True)
|
|
491
|
+
xs, ys = (out[..., [0, 2]], out[..., [1, 3]]) if out.ndim == 2 else (out[..., 0], out[..., 1])
|
|
492
|
+
new_xs, new_ys = (left + xs * w) / new_w, (top + ys * h) / new_h
|
|
493
|
+
if out.ndim == 2:
|
|
494
|
+
out[..., [0, 2]], out[..., [1, 3]] = new_xs, new_ys
|
|
495
|
+
else:
|
|
496
|
+
out[..., 0], out[..., 1] = new_xs, new_ys
|
|
497
|
+
return out
|
|
498
|
+
|
|
499
|
+
def forward(self, sample: Sample) -> Sample:
|
|
500
|
+
if torch.rand(1) >= self.p:
|
|
501
|
+
return sample
|
|
502
|
+
img = sample.image # (C, H, W)
|
|
503
|
+
_, h, w = img.shape
|
|
504
|
+
top, bottom, left, right = (torch.rand(4) * self.max_ratio * h).long().tolist()
|
|
505
|
+
new_h, new_w = top + h + bottom, left + w + right
|
|
506
|
+
# Background color: the median color of the border pixels
|
|
507
|
+
border = torch.cat([img[:, 0], img[:, -1], img[:, :, 0], img[:, :, -1]], dim=1)
|
|
508
|
+
background = border.median(dim=1).values
|
|
509
|
+
out = background[:, None, None].repeat(1, new_h, new_w)
|
|
510
|
+
out[:, top : top + h, left : left + w] = img
|
|
511
|
+
|
|
512
|
+
target = sample.target
|
|
513
|
+
if isinstance(target, np.ndarray):
|
|
514
|
+
target = self._pad_target(target, (left, top), (h, w), (new_h, new_w))
|
|
515
|
+
elif isinstance(target, dict):
|
|
516
|
+
target = {
|
|
517
|
+
key: self._pad_target(value, (left, top), (h, w), (new_h, new_w))
|
|
518
|
+
if isinstance(value, np.ndarray)
|
|
519
|
+
else value
|
|
520
|
+
for key, value in target.items()
|
|
521
|
+
}
|
|
522
|
+
# The padded areas are not valid image content
|
|
523
|
+
mask = None if sample.mask is None else pad(sample.mask, (left, right, top, bottom), value=False)
|
|
524
|
+
return sample.replace(image=out, target=target, mask=mask)
|
|
525
|
+
|
|
526
|
+
def extra_repr(self) -> str:
|
|
527
|
+
return f"max_ratio={self.max_ratio}, p={self.p}"
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def _apply_float_photometric(sample: Sample, fn) -> Sample:
|
|
531
|
+
"""Run a photometric function expecting a float image in [0, 1] on a float or uint8 sample."""
|
|
532
|
+
if sample.image.dtype == torch.uint8:
|
|
533
|
+
out = (255 * fn(sample.image.to(dtype=torch.float32) / 255)).round().clip(0, 255).to(dtype=torch.uint8)
|
|
534
|
+
else:
|
|
535
|
+
out = fn(sample.image).clip(0, 1)
|
|
536
|
+
return sample.replace(image=out)
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
class RandomGlare(torch.nn.Module):
|
|
540
|
+
"""Adds soft bright reflections to the image, like a light source mirrored on a photographed screen or a
|
|
541
|
+
glossy sheet
|
|
542
|
+
|
|
543
|
+
>>> import torch
|
|
544
|
+
>>> from doctr.transforms import RandomGlare
|
|
545
|
+
>>> from doctr.utils import Sample
|
|
546
|
+
>>> transfo = RandomGlare((0.2, 0.7))
|
|
547
|
+
>>> out = transfo(Sample(image=torch.rand((3, 64, 64))))
|
|
548
|
+
|
|
549
|
+
Args:
|
|
550
|
+
opacity_range: minimum and maximum strength of the reflections
|
|
551
|
+
num_spots: minimum and maximum number of reflections
|
|
552
|
+
"""
|
|
553
|
+
|
|
554
|
+
def __init__(self, opacity_range: tuple[float, float] | None = None, num_spots: tuple[int, int] = (1, 3)) -> None:
|
|
555
|
+
super().__init__()
|
|
556
|
+
self.opacity_range = opacity_range if isinstance(opacity_range, tuple) else (0.2, 0.7)
|
|
557
|
+
self.num_spots = num_spots
|
|
558
|
+
|
|
559
|
+
def __call__(self, sample: Sample) -> Sample:
|
|
560
|
+
return _apply_float_photometric(sample, lambda img: random_glare(img, self.opacity_range, self.num_spots))
|
|
561
|
+
|
|
562
|
+
def extra_repr(self) -> str:
|
|
563
|
+
return f"opacity_range={self.opacity_range}, num_spots={self.num_spots}"
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
class RandomLighting(torch.nn.Module):
|
|
567
|
+
"""Multiplies the image by a smooth low-frequency brightness field: uneven lighting, the shading of a crumpled
|
|
568
|
+
or curved sheet, vignetting
|
|
569
|
+
|
|
570
|
+
>>> import torch
|
|
571
|
+
>>> from doctr.transforms import RandomLighting
|
|
572
|
+
>>> from doctr.utils import Sample
|
|
573
|
+
>>> transfo = RandomLighting((0.1, 0.4))
|
|
574
|
+
>>> out = transfo(Sample(image=torch.rand((3, 64, 64))))
|
|
575
|
+
|
|
576
|
+
Args:
|
|
577
|
+
strength_range: minimum and maximum amplitude of the field (0.3 = brightness between 0.7 and 1.3)
|
|
578
|
+
"""
|
|
579
|
+
|
|
580
|
+
def __init__(self, strength_range: tuple[float, float] | None = None) -> None:
|
|
581
|
+
super().__init__()
|
|
582
|
+
self.strength_range = strength_range if isinstance(strength_range, tuple) else (0.1, 0.4)
|
|
583
|
+
|
|
584
|
+
def __call__(self, sample: Sample) -> Sample:
|
|
585
|
+
return _apply_float_photometric(sample, lambda img: random_lighting(img, self.strength_range))
|
|
586
|
+
|
|
587
|
+
def extra_repr(self) -> str:
|
|
588
|
+
return f"strength_range={self.strength_range}"
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
class RandomPerspective(torch.nn.Module):
|
|
592
|
+
"""Warps the image and its boxes with a random perspective, as if the page were photographed at an angle
|
|
593
|
+
|
|
594
|
+
>>> import numpy as np
|
|
595
|
+
>>> import torch
|
|
596
|
+
>>> from doctr.transforms import RandomPerspective
|
|
597
|
+
>>> from doctr.utils import Sample
|
|
598
|
+
>>> transfo = RandomPerspective(distortion=0.2)
|
|
599
|
+
>>> out = transfo(Sample(image=torch.rand((3, 64, 64)), target=np.array([[0.1, 0.1, 0.5, 0.5]])))
|
|
600
|
+
|
|
601
|
+
Args:
|
|
602
|
+
distortion: maximum relative displacement of every image corner (0.2 = up to 20% of the width / height)
|
|
603
|
+
"""
|
|
604
|
+
|
|
605
|
+
def __init__(self, distortion: float = 0.2) -> None:
|
|
606
|
+
super().__init__()
|
|
607
|
+
self.distortion = distortion
|
|
608
|
+
|
|
609
|
+
def __call__(self, sample: Sample) -> Sample:
|
|
610
|
+
img, target, mask = sample.image, sample.target, sample.mask
|
|
611
|
+
if target is None:
|
|
612
|
+
w_img, _, w_mask = perspective_sample(img, np.zeros((0, 4), dtype=np.float32), self.distortion, mask)
|
|
613
|
+
return sample.replace(image=w_img, mask=w_mask)
|
|
614
|
+
if isinstance(target, dict):
|
|
615
|
+
# Same random warp for every class: the corners are drawn from numpy's RNG, so restoring its state
|
|
616
|
+
# before every class reproduces the same transformation for the image and each geometry array
|
|
617
|
+
state = np.random.get_state()
|
|
618
|
+
out_target: dict[str, np.ndarray] = {}
|
|
619
|
+
w_img, w_mask = img, mask
|
|
620
|
+
for cls_name, arr in target.items():
|
|
621
|
+
np.random.set_state(state)
|
|
622
|
+
w_img, w_arr, w_mask = perspective_sample(img, arr, self.distortion, mask)
|
|
623
|
+
out_target[cls_name] = w_arr
|
|
624
|
+
return sample.replace(image=w_img, mask=w_mask, target=out_target)
|
|
625
|
+
w_img, w_target, w_mask = perspective_sample(img, target, self.distortion, mask)
|
|
626
|
+
return sample.replace(image=w_img, mask=w_mask, target=w_target)
|
|
627
|
+
|
|
628
|
+
def extra_repr(self) -> str:
|
|
629
|
+
return f"distortion={self.distortion}"
|