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.
Files changed (143) hide show
  1. doctr/cli/__init__.py +0 -0
  2. doctr/cli/main.py +669 -0
  3. doctr/datasets/__init__.py +2 -0
  4. doctr/datasets/coco_text.py +4 -2
  5. doctr/datasets/cord.py +2 -1
  6. doctr/datasets/datasets/base.py +12 -24
  7. doctr/datasets/datasets/pytorch.py +14 -4
  8. doctr/datasets/detection.py +14 -3
  9. doctr/datasets/doc_artefacts.py +2 -1
  10. doctr/datasets/funsd.py +2 -1
  11. doctr/datasets/generator/base.py +121 -37
  12. doctr/datasets/generator/pytorch.py +5 -6
  13. doctr/datasets/ic03.py +9 -7
  14. doctr/datasets/ic13.py +4 -2
  15. doctr/datasets/iiit5k.py +2 -1
  16. doctr/datasets/iiithws.py +4 -2
  17. doctr/datasets/imgur5k.py +4 -2
  18. doctr/datasets/layout.py +129 -0
  19. doctr/datasets/mjsynth.py +4 -2
  20. doctr/datasets/ocr.py +2 -1
  21. doctr/datasets/orientation.py +2 -1
  22. doctr/datasets/recognition.py +5 -4
  23. doctr/datasets/sroie.py +2 -1
  24. doctr/datasets/svhn.py +2 -1
  25. doctr/datasets/svt.py +10 -8
  26. doctr/datasets/synthtext.py +2 -1
  27. doctr/datasets/table_structure.py +97 -0
  28. doctr/datasets/utils.py +104 -21
  29. doctr/datasets/vocabs.py +320 -148
  30. doctr/datasets/wildreceipt.py +4 -2
  31. doctr/file_utils.py +3 -1
  32. doctr/io/__init__.py +3 -0
  33. doctr/io/elements.py +381 -271
  34. doctr/io/exporters.py +1915 -0
  35. doctr/io/figures.py +313 -0
  36. doctr/io/image/base.py +54 -7
  37. doctr/io/image/pytorch.py +13 -5
  38. doctr/io/pdf.py +6 -5
  39. doctr/io/reader.py +268 -18
  40. doctr/io/sources.py +636 -0
  41. doctr/models/__init__.py +3 -0
  42. doctr/models/_utils.py +206 -13
  43. doctr/models/builder.py +590 -137
  44. doctr/models/classification/__init__.py +3 -0
  45. doctr/models/classification/hgnetv2/__init__.py +1 -0
  46. doctr/models/classification/hgnetv2/pytorch.py +352 -0
  47. doctr/models/classification/magc_resnet/pytorch.py +1 -1
  48. doctr/models/classification/mobilenet/pytorch.py +6 -6
  49. doctr/models/classification/predictor/pytorch.py +34 -2
  50. doctr/models/classification/resnet/pytorch.py +5 -5
  51. doctr/models/classification/starnet/__init__.py +1 -0
  52. doctr/models/classification/starnet/pytorch.py +202 -0
  53. doctr/models/classification/textnet/pytorch.py +6 -5
  54. doctr/models/classification/vgg/pytorch.py +3 -2
  55. doctr/models/classification/vip/layers/pytorch.py +4 -4
  56. doctr/models/classification/vip/pytorch.py +4 -4
  57. doctr/models/classification/vit/pytorch.py +3 -3
  58. doctr/models/classification/vit_det/__init__.py +1 -0
  59. doctr/models/classification/vit_det/layers/__init__.py +1 -0
  60. doctr/models/classification/vit_det/layers/pytorch.py +215 -0
  61. doctr/models/classification/vit_det/pytorch.py +346 -0
  62. doctr/models/classification/zoo.py +14 -2
  63. doctr/models/detection/_utils/base.py +23 -7
  64. doctr/models/detection/core.py +32 -18
  65. doctr/models/detection/differentiable_binarization/base.py +23 -9
  66. doctr/models/detection/differentiable_binarization/pytorch.py +10 -4
  67. doctr/models/detection/fast/base.py +22 -6
  68. doctr/models/detection/fast/pytorch.py +24 -11
  69. doctr/models/detection/linknet/base.py +22 -6
  70. doctr/models/detection/linknet/pytorch.py +10 -3
  71. doctr/models/detection/predictor/pytorch.py +43 -2
  72. doctr/models/detection/zoo.py +6 -2
  73. doctr/models/factory/hub.py +59 -41
  74. doctr/models/formula/__init__.py +2 -0
  75. doctr/models/formula/formulanet/__init__.py +2 -0
  76. doctr/models/formula/formulanet/base.py +70 -0
  77. doctr/models/formula/formulanet/pytorch.py +587 -0
  78. doctr/models/formula/predictor/__init__.py +1 -0
  79. doctr/models/formula/predictor/pytorch.py +132 -0
  80. doctr/models/formula/zoo.py +102 -0
  81. doctr/models/kie_predictor/base.py +23 -1
  82. doctr/models/kie_predictor/pytorch.py +87 -15
  83. doctr/models/layout/__init__.py +2 -0
  84. doctr/models/layout/lw_detr/__init__.py +1 -0
  85. doctr/models/layout/lw_detr/base.py +309 -0
  86. doctr/models/layout/lw_detr/layers/__init__.py +1 -0
  87. doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
  88. doctr/models/layout/lw_detr/pytorch.py +895 -0
  89. doctr/models/layout/predictor/__init__.py +1 -0
  90. doctr/models/layout/predictor/pytorch.py +114 -0
  91. doctr/models/layout/zoo.py +94 -0
  92. doctr/models/modules/layers/pytorch.py +139 -3
  93. doctr/models/modules/transformer/pytorch.py +151 -31
  94. doctr/models/predictor/base.py +415 -17
  95. doctr/models/predictor/pytorch.py +109 -12
  96. doctr/models/preprocessor/pytorch.py +82 -25
  97. doctr/models/reading_order/__init__.py +1 -0
  98. doctr/models/reading_order/base.py +1127 -0
  99. doctr/models/recognition/core.py +14 -1
  100. doctr/models/recognition/crnn/pytorch.py +40 -16
  101. doctr/models/recognition/master/base.py +4 -1
  102. doctr/models/recognition/master/pytorch.py +84 -22
  103. doctr/models/recognition/parseq/base.py +4 -1
  104. doctr/models/recognition/parseq/pytorch.py +126 -25
  105. doctr/models/recognition/predictor/_utils.py +131 -14
  106. doctr/models/recognition/predictor/pytorch.py +68 -12
  107. doctr/models/recognition/sar/pytorch.py +21 -7
  108. doctr/models/recognition/utils.py +80 -50
  109. doctr/models/recognition/viptr/pytorch.py +38 -14
  110. doctr/models/recognition/vitstr/base.py +4 -1
  111. doctr/models/recognition/vitstr/pytorch.py +11 -7
  112. doctr/models/recognition/zoo.py +36 -9
  113. doctr/models/table_structure/__init__.py +2 -0
  114. doctr/models/table_structure/grid.py +430 -0
  115. doctr/models/table_structure/predictor/__init__.py +1 -0
  116. doctr/models/table_structure/predictor/pytorch.py +231 -0
  117. doctr/models/table_structure/tablecenternet/__init__.py +2 -0
  118. doctr/models/table_structure/tablecenternet/base.py +675 -0
  119. doctr/models/table_structure/tablecenternet/pytorch.py +525 -0
  120. doctr/models/table_structure/zoo.py +87 -0
  121. doctr/models/utils/pytorch.py +381 -25
  122. doctr/models/zoo.py +141 -4
  123. doctr/transforms/functional/base.py +6 -0
  124. doctr/transforms/functional/pytorch.py +134 -6
  125. doctr/transforms/modules/base.py +261 -82
  126. doctr/transforms/modules/pytorch.py +396 -76
  127. doctr/utils/common_types.py +21 -1
  128. doctr/utils/data.py +24 -11
  129. doctr/utils/fonts.py +64 -17
  130. doctr/utils/geometry.py +167 -28
  131. doctr/utils/metrics.py +481 -19
  132. doctr/utils/multithreading.py +127 -4
  133. doctr/utils/reconstitution.py +696 -132
  134. doctr/utils/visualization.py +73 -10
  135. doctr/version.py +1 -1
  136. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/METADATA +119 -249
  137. python_doctr-1.2.0.dist-info/RECORD +191 -0
  138. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
  139. python_doctr-1.2.0.dist-info/entry_points.txt +2 -0
  140. python_doctr-1.0.1.dist-info/RECORD +0 -149
  141. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
  142. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
  143. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
@@ -10,23 +10,32 @@ from typing import Any
10
10
 
11
11
  import numpy as np
12
12
 
13
+ from doctr.utils.common_types import Sample
13
14
  from doctr.utils.repr import NestedObject
14
15
 
15
16
  from .. import functional as F
16
17
 
17
- __all__ = ["SampleCompose", "ImageTransform", "ColorInversion", "OneOf", "RandomApply", "RandomRotate", "RandomCrop"]
18
+ __all__ = [
19
+ "SampleCompose",
20
+ "ImageTransform",
21
+ "ColorInversion",
22
+ "OneOf",
23
+ "RandomApply",
24
+ "RandomRotate",
25
+ "RandomCrop",
26
+ "ImageTorchvisionTransform",
27
+ ]
18
28
 
19
29
 
20
30
  class SampleCompose(NestedObject):
21
31
  """Implements a wrapper that will apply transformations sequentially on both image and target
22
32
 
23
- .. code:: python
24
-
25
- >>> import numpy as np
26
- >>> import torch
27
- >>> from doctr.transforms import SampleCompose, ImageTransform, ColorInversion, RandomRotate
28
- >>> transfos = SampleCompose([ImageTransform(ColorInversion((32, 32))), RandomRotate(30)])
29
- >>> out, out_boxes = transfos(torch.rand(8, 64, 64, 3), np.zeros((2, 4)))
33
+ >>> import numpy as np
34
+ >>> import torch
35
+ >>> from doctr.transforms import SampleCompose, ImageTransform, ColorInversion, RandomRotate
36
+ >>> from doctr.utils import Sample
37
+ >>> transfos = SampleCompose([ImageTransform(ColorInversion((32, 32))), RandomRotate(30)])
38
+ >>> out, out_boxes = transfos(Sample(image=torch.rand(8, 64, 64, 3), target=np.zeros((2, 4))))
30
39
 
31
40
  Args:
32
41
  transforms: list of transformation modules
@@ -34,25 +43,23 @@ class SampleCompose(NestedObject):
34
43
 
35
44
  _children_names: list[str] = ["sample_transforms"]
36
45
 
37
- def __init__(self, transforms: list[Callable[[Any, Any], tuple[Any, Any]]]) -> None:
46
+ def __init__(self, transforms: list[Callable[[Sample], Sample]]) -> None:
38
47
  self.sample_transforms = transforms
39
48
 
40
- def __call__(self, x: Any, target: Any) -> tuple[Any, Any]:
49
+ def __call__(self, sample: Sample) -> Sample:
41
50
  for t in self.sample_transforms:
42
- x, target = t(x, target)
43
-
44
- return x, target
51
+ sample = t(sample)
52
+ return sample
45
53
 
46
54
 
47
55
  class ImageTransform(NestedObject):
48
56
  """Implements a transform wrapper to turn an image-only transformation into an image+target transform
49
57
 
50
- .. code:: python
51
-
52
- >>> import torch
53
- >>> from doctr.transforms import ImageTransform, ColorInversion
54
- >>> transfo = ImageTransform(ColorInversion((32, 32)))
55
- >>> out, _ = transfo(torch.rand(8, 64, 64, 3), None)
58
+ >>> import torch
59
+ >>> from doctr.transforms import ImageTransform, ColorInversion
60
+ >>> from doctr.utils import Sample
61
+ >>> transfo = ImageTransform(ColorInversion((32, 32)))
62
+ >>> out = transfo(Sample(image=torch.rand(8, 64, 64, 3)))
56
63
 
57
64
  Args:
58
65
  transform: the image transformation module to wrap
@@ -63,21 +70,44 @@ class ImageTransform(NestedObject):
63
70
  def __init__(self, transform: Callable[[Any], Any]) -> None:
64
71
  self.img_transform = transform
65
72
 
66
- def __call__(self, img: Any, target: Any) -> tuple[Any, Any]:
67
- img = self.img_transform(img)
68
- return img, target
73
+ def __call__(self, sample: Sample) -> Sample:
74
+ img = self.img_transform(sample)
75
+ return sample.replace(image=img)
76
+
77
+
78
+ class ImageTorchvisionTransform(NestedObject):
79
+ """Implements a transform wrapper to turn a torchvision image-only transformation into an image+target transform
80
+
81
+ >>> import torch
82
+ >>> from torchvision import transforms
83
+ >>> from doctr.transforms import ImageTorchvisionTransform
84
+ >>> from doctr.utils import Sample
85
+ >>> transfo = ImageTorchvisionTransform(transforms.ColorJitter(brightness=0.5))
86
+ >>> out, _ = transfo(Sample(image=torch.rand(8, 64, 64, 3)))
87
+
88
+ Args:
89
+ transform: the torchvision image transformation module to wrap
90
+ """
91
+
92
+ _children_names: list[str] = ["img_transform"]
93
+
94
+ def __init__(self, transform: Callable[[Any], Any]) -> None:
95
+ self.img_transform = transform
96
+
97
+ def __call__(self, sample: Sample) -> Sample:
98
+ img = self.img_transform(sample.image)
99
+ return sample.replace(image=img)
69
100
 
70
101
 
71
102
  class ColorInversion(NestedObject):
72
103
  """Applies the following tranformation to a tensor (image or batch of images):
73
104
  convert to grayscale, colorize (shift 0-values randomly), and then invert colors
74
105
 
75
- .. code:: python
76
-
77
- >>> import torch
78
- >>> from doctr.transforms import ColorInversion
79
- >>> transfo = ColorInversion(min_val=0.6)
80
- >>> out = transfo(torch.rand(8, 64, 64, 3))
106
+ >>> import torch
107
+ >>> from doctr.transforms import ColorInversion
108
+ >>> from doctr.utils import Sample
109
+ >>> transfo = ColorInversion(min_val=0.6)
110
+ >>> out = transfo(Sample(image=torch.rand(8, 64, 64, 3)))
81
111
 
82
112
  Args:
83
113
  min_val: range [min_val, 1] to colorize RGB pixels
@@ -89,19 +119,19 @@ class ColorInversion(NestedObject):
89
119
  def extra_repr(self) -> str:
90
120
  return f"min_val={self.min_val}"
91
121
 
92
- def __call__(self, img: Any) -> Any:
93
- return F.invert_colors(img, self.min_val)
122
+ def __call__(self, sample: Sample) -> Sample:
123
+ out = F.invert_colors(sample.image, self.min_val)
124
+ return sample.replace(image=out)
94
125
 
95
126
 
96
127
  class OneOf(NestedObject):
97
128
  """Randomly apply one of the input transformations
98
129
 
99
- .. code:: python
100
-
101
- >>> import torch
102
- >>> from doctr.transforms import OneOf
103
- >>> transfo = OneOf([JpegQuality(), Gamma()])
104
- >>> out = transfo(torch.rand(1, 64, 64, 3))
130
+ >>> import torch
131
+ >>> from doctr.transforms import OneOf, JpegQuality, Gamma
132
+ >>> from doctr.utils import Sample
133
+ >>> transfo = OneOf([JpegQuality(), Gamma()])
134
+ >>> out = transfo(Sample(image=torch.rand(1, 64, 64, 3)))
105
135
 
106
136
  Args:
107
137
  transforms: list of transformations, one only will be picked
@@ -109,42 +139,39 @@ class OneOf(NestedObject):
109
139
 
110
140
  _children_names: list[str] = ["transforms"]
111
141
 
112
- def __init__(self, transforms: list[Callable[[Any], Any]]) -> None:
142
+ def __init__(self, transforms: list[Callable[[Sample], Sample]]) -> None:
113
143
  self.transforms = transforms
114
144
 
115
- def __call__(self, img: Any, target: np.ndarray | None = None) -> Any | tuple[Any, np.ndarray]:
116
- # Pick transformation
145
+ def __call__(self, sample: Sample) -> Sample:
117
146
  transfo = self.transforms[int(random.random() * len(self.transforms))]
118
- # Apply
119
- return transfo(img) if target is None else transfo(img, target) # type: ignore[call-arg]
147
+ return transfo(sample)
120
148
 
121
149
 
122
150
  class RandomApply(NestedObject):
123
151
  """Apply with a probability p the input transformation
124
152
 
125
- .. code:: python
126
-
127
- >>> import torch
128
- >>> from doctr.transforms import RandomApply
129
- >>> transfo = RandomApply(Gamma(), p=.5)
130
- >>> out = transfo(torch.rand(1, 64, 64, 3))
153
+ >>> import torch
154
+ >>> from doctr.transforms import RandomApply, Gamma
155
+ >>> from doctr.utils import Sample
156
+ >>> transfo = RandomApply(Gamma(), p=.5)
157
+ >>> out = transfo(Sample(image=torch.rand(1, 64, 64, 3), target=np.array([[0.1, 0.1, 0.9, 0.9]]), mask=None))
131
158
 
132
159
  Args:
133
160
  transform: transformation to apply
134
161
  p: probability to apply
135
162
  """
136
163
 
137
- def __init__(self, transform: Callable[[Any], Any], p: float = 0.5) -> None:
164
+ def __init__(self, transform: Callable[[Sample], Sample], p: float = 0.5) -> None:
138
165
  self.transform = transform
139
166
  self.p = p
140
167
 
141
168
  def extra_repr(self) -> str:
142
169
  return f"transform={self.transform}, p={self.p}"
143
170
 
144
- def __call__(self, img: Any, target: np.ndarray | None = None) -> Any | tuple[Any, np.ndarray]:
171
+ def __call__(self, sample: Sample) -> Sample:
145
172
  if random.random() < self.p:
146
- return self.transform(img) if target is None else self.transform(img, target) # type: ignore[call-arg]
147
- return img if target is None else (img, target)
173
+ return self.transform(sample)
174
+ return sample
148
175
 
149
176
 
150
177
  class RandomRotate(NestedObject):
@@ -153,6 +180,11 @@ class RandomRotate(NestedObject):
153
180
  .. image:: https://doctr-static.mindee.com/models?id=v0.4.0/rotation_illustration.png&src=0
154
181
  :align: center
155
182
 
183
+ >>> import torch
184
+ >>> from doctr.transforms import RandomRotate
185
+ >>> transfo = RandomRotate(max_angle=30, expand=True)
186
+ >>> out = transfo(Sample(image=torch.rand(1, 64, 64, 3), target=np.array([[0.1, 0.1, 0.9, 0.9]]), mask=None))
187
+
156
188
  Args:
157
189
  max_angle: maximum angle for rotation, in degrees. Angles will be uniformly picked in [-max_angle, max_angle]
158
190
  expand: whether the image should be padded before the rotation
@@ -165,17 +197,79 @@ class RandomRotate(NestedObject):
165
197
  def extra_repr(self) -> str:
166
198
  return f"max_angle={self.max_angle}, expand={self.expand}"
167
199
 
168
- def __call__(self, img: Any, target: np.ndarray) -> tuple[Any, np.ndarray]:
169
- angle = random.uniform(-self.max_angle, self.max_angle)
200
+ def _rotate_image_only(self, img: Any, angle: float) -> Any:
201
+ dummy_box = np.array([[0, 0, 1, 1]], dtype=np.float32)
202
+ r_img, _ = F.rotate_sample(img, dummy_box, angle, self.expand)
203
+ return r_img
204
+
205
+ def _rotate_array(self, img: Any, target: np.ndarray, angle: float):
206
+ is_polygon = target.shape[1:] == (4, 2)
207
+
170
208
  r_img, r_polys = F.rotate_sample(img, target, angle, self.expand)
171
- # Removes deleted boxes
209
+
172
210
  is_kept = (r_polys.max(1) > r_polys.min(1)).sum(1) == 2
173
- return r_img, r_polys[is_kept]
211
+ r_polys = r_polys[is_kept]
212
+
213
+ # convert back if input was boxes
214
+ if not is_polygon:
215
+ x1y1 = r_polys.min(axis=1)
216
+ x2y2 = r_polys.max(axis=1)
217
+ return r_img, np.concatenate([x1y1, x2y2], axis=1)
218
+
219
+ return r_img, r_polys
220
+
221
+ def __call__(self, sample: Sample) -> Sample:
222
+ angle = random.uniform(-self.max_angle, self.max_angle)
223
+
224
+ img = sample.image
225
+ target = sample.target
226
+ mask = sample.mask
227
+
228
+ r_mask = None
229
+ if mask is not None:
230
+ r_mask, _ = F.rotate_sample(
231
+ mask.unsqueeze(0), np.array([[0, 0, 1, 1]], dtype=np.float32), angle, self.expand
232
+ )
233
+ # Remove the axis added for the rotation, so the mask keeps its shape like in the other transforms
234
+ r_mask = r_mask.squeeze(0)
235
+
236
+ if target is None:
237
+ return sample.replace(image=self._rotate_image_only(img, angle), mask=r_mask)
238
+
239
+ if isinstance(target, dict):
240
+ rotated_targets = {}
241
+ rotated_img = None
242
+
243
+ for cls_name, arr in target.items():
244
+ if len(arr) == 0:
245
+ rotated_targets[cls_name] = arr.copy()
246
+ continue
247
+
248
+ r_img, r_arr = self._rotate_array(img, arr, angle)
249
+ if rotated_img is None:
250
+ rotated_img = r_img
251
+ rotated_targets[cls_name] = r_arr
252
+
253
+ # Every class may be empty: the image (and its mask) still have to be rotated
254
+ final_img = rotated_img if rotated_img is not None else self._rotate_image_only(img, angle)
255
+ return sample.replace(image=final_img, mask=r_mask, target=rotated_targets)
256
+
257
+ if len(target) == 0:
258
+ return sample.replace(image=self._rotate_image_only(img, angle), mask=r_mask, target=target.copy())
259
+
260
+ r_img, r_target = self._rotate_array(img, target, angle)
261
+ return sample.replace(image=r_img, mask=r_mask, target=r_target)
174
262
 
175
263
 
176
264
  class RandomCrop(NestedObject):
177
265
  """Randomly crop a tensor image and its boxes
178
266
 
267
+ >>> import torch
268
+ >>> from doctr.transforms import RandomCrop
269
+ >>> from doctr.utils import Sample
270
+ >>> transfo = RandomCrop(scale=(0.5, 1.0), ratio=(0.75, 1.33))
271
+ >>> out = transfo(Sample(image=torch.rand(1, 64, 64, 3), target=np.array([[0.1, 0.1, 0.9, 0.9]]), mask=None))
272
+
179
273
  Args:
180
274
  scale: tuple of floats, relative (min_area, max_area) of the crop
181
275
  ratio: tuple of float, relative (min_ratio, max_ratio) where ratio = h/w
@@ -188,39 +282,124 @@ class RandomCrop(NestedObject):
188
282
  def extra_repr(self) -> str:
189
283
  return f"scale={self.scale}, ratio={self.ratio}"
190
284
 
191
- def __call__(self, img: Any, target: np.ndarray) -> tuple[Any, np.ndarray]:
285
+ def _crop_image_only(self, img: Any, crop_box: tuple[float, float, float, float]) -> Any:
286
+ dummy_box = np.array([[0, 0, 1, 1]], dtype=np.float32)
287
+ cropped_img, _ = F.crop_detection(img, dummy_box, crop_box)
288
+ return cropped_img
289
+
290
+ def _crop_array(
291
+ self, img: Any, target: np.ndarray, crop_box: tuple[float, float, float, float]
292
+ ) -> tuple[Any, np.ndarray]:
293
+ is_polygon = target.shape[1:] == (4, 2)
294
+
295
+ if is_polygon:
296
+ cropped_img, _ = F.crop_detection(
297
+ img,
298
+ np.concatenate((np.min(target, axis=1), np.max(target, axis=1)), axis=1),
299
+ crop_box,
300
+ )
301
+
302
+ cropped_polys = target.copy()
303
+
304
+ crop_w = crop_box[2] - crop_box[0]
305
+ crop_h = crop_box[3] - crop_box[1]
306
+
307
+ # Reproject coordinates into cropped frame
308
+ cropped_polys[..., 0] = (cropped_polys[..., 0] - crop_box[0]) / crop_w
309
+ cropped_polys[..., 1] = (cropped_polys[..., 1] - crop_box[1]) / crop_h
310
+
311
+ # Keep polygons with at least partial visibility
312
+ poly_min = np.min(cropped_polys, axis=1)
313
+ poly_max = np.max(cropped_polys, axis=1)
314
+ is_kept = (poly_max[:, 0] > 0) & (poly_min[:, 0] < 1) & (poly_max[:, 1] > 0) & (poly_min[:, 1] < 1)
315
+ cropped_polys = cropped_polys[is_kept]
316
+
317
+ if cropped_polys.shape[0] == 0:
318
+ return img, target
319
+
320
+ return cropped_img, np.clip(cropped_polys, 0, 1)
321
+
322
+ # For detection boxes, we can directly crop and clip them
323
+ cropped_img, crop_boxes = F.crop_detection(img, target, crop_box)
324
+
325
+ if crop_boxes.shape[0] == 0:
326
+ return img, target
327
+
328
+ return cropped_img, np.clip(crop_boxes, 0, 1)
329
+
330
+ def __call__(self, sample: Sample) -> Sample:
192
331
  scale = random.uniform(self.scale[0], self.scale[1])
193
332
  ratio = random.uniform(self.ratio[0], self.ratio[1])
194
333
 
195
- height, width = img.shape[-2:]
334
+ img = sample.image
335
+ target = sample.target
336
+ mask = sample.mask
337
+
338
+ h, w = img.shape[-2:]
339
+
340
+ crop_area = scale * w * h
341
+ aspect_ratio = ratio * (w / h)
342
+
343
+ crop_w = int(round(math.sqrt(crop_area * aspect_ratio)))
344
+ crop_h = int(round(math.sqrt(crop_area / aspect_ratio)))
345
+
346
+ crop_w = min(crop_w, w)
347
+ crop_h = min(crop_h, h)
348
+
349
+ x = random.randint(0, w - crop_w)
350
+ y = random.randint(0, h - crop_h)
351
+
352
+ crop_box = (
353
+ x / w,
354
+ y / h,
355
+ (x + crop_w) / w,
356
+ (y + crop_h) / h,
357
+ )
358
+
359
+ if target is None:
360
+ r_img = self._crop_image_only(img, crop_box)
361
+ r_mask = self._crop_image_only(mask, crop_box) if mask is not None else None
362
+ return sample.replace(image=r_img, mask=r_mask)
196
363
 
197
- # Calculate crop size
198
- crop_area = scale * width * height
199
- aspect_ratio = ratio * (width / height)
200
- crop_width = int(round(math.sqrt(crop_area * aspect_ratio)))
201
- crop_height = int(round(math.sqrt(crop_area / aspect_ratio)))
364
+ if isinstance(target, dict):
365
+ cropped_targets = {}
366
+ cropped_img = None
367
+ crop_rejected = False
202
368
 
203
- # Ensure crop size does not exceed image dimensions
204
- crop_width = min(crop_width, width)
205
- crop_height = min(crop_height, height)
369
+ for cls_name, arr in target.items():
370
+ if len(arr) == 0:
371
+ cropped_targets[cls_name] = arr.copy()
372
+ continue
206
373
 
207
- # Randomly select crop position
208
- x = random.randint(0, width - crop_width)
209
- y = random.randint(0, height - crop_height)
374
+ c_img, c_arr = self._crop_array(img, arr, crop_box)
210
375
 
211
- # relative crop box
212
- crop_box = (x / width, y / height, (x + crop_width) / width, (y + crop_height) / height)
213
- if target.shape[1:] == (4, 2):
214
- min_xy = np.min(target, axis=1)
215
- max_xy = np.max(target, axis=1)
216
- _target = np.concatenate((min_xy, max_xy), axis=1)
376
+ if c_img is img:
377
+ crop_rejected = True
378
+ break
379
+
380
+ if cropped_img is None:
381
+ cropped_img = c_img
382
+
383
+ cropped_targets[cls_name] = c_arr
384
+
385
+ if crop_rejected or cropped_img is None:
386
+ return sample.replace(
387
+ image=img,
388
+ mask=mask,
389
+ target={key: value.copy() for key, value in target.items()},
390
+ )
391
+
392
+ r_mask = self._crop_image_only(mask, crop_box) if mask is not None else None
393
+ return sample.replace(image=cropped_img, mask=r_mask, target=cropped_targets)
394
+
395
+ if len(target) == 0:
396
+ # Same as a dict target without any box: keep the sample as is
397
+ return sample.replace(image=img, mask=mask, target=target.copy())
398
+
399
+ c_img, c_target = self._crop_array(img, target, crop_box)
400
+ if c_img is img:
401
+ r_mask = mask
217
402
  else:
218
- _target = target
403
+ r_mask = self._crop_image_only(mask, crop_box) if mask is not None else None
219
404
 
220
- # Crop image and targets
221
- croped_img, crop_boxes = F.crop_detection(img, _target, crop_box)
222
- # hard fallback if no box is kept
223
- if crop_boxes.shape[0] == 0:
224
- return img, target
225
- # clip boxes
226
- return croped_img, np.clip(crop_boxes, 0, 1)
405
+ return sample.replace(image=c_img, mask=r_mask, target=c_target)