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
doctr/io/figures.py ADDED
@@ -0,0 +1,313 @@
1
+ # Copyright (C) 2021-2026, Mindee.
2
+
3
+ # This program is licensed under the Apache License 2.0.
4
+ # See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
5
+
6
+ import hashlib
7
+ import os
8
+ import weakref
9
+ from base64 import b64encode
10
+ from pathlib import Path
11
+ from typing import TYPE_CHECKING, Any
12
+ from urllib.parse import quote
13
+
14
+ import cv2
15
+ import numpy as np
16
+
17
+ from doctr.utils.geometry import extract_crops, extract_rcrops
18
+
19
+ if TYPE_CHECKING: # pragma: no cover
20
+ from doctr.io.elements import LayoutElement, Page
21
+
22
+ __all__ = [
23
+ "IMAGE_FORMATS",
24
+ "IMAGE_MODES",
25
+ "FigureEncoder",
26
+ "crop_layout_region",
27
+ "encode_crop",
28
+ "is_picture_label",
29
+ "is_picture_region",
30
+ "picture_regions",
31
+ ]
32
+
33
+ IMAGE_MODES = ("none", "placeholder", "embedded", "referenced")
34
+ IMAGE_FORMATS = ("png", "jpg", "jpeg", "webp")
35
+
36
+
37
+ def is_picture_label(label: str | None) -> bool:
38
+ """Check whether a layout label denotes a figure, i.e. a float that is not a table (e.g. 'Picture', 'Chart')
39
+
40
+ Args:
41
+ label: the layout label
42
+
43
+ Returns:
44
+ True for a figure label
45
+ """
46
+ from doctr.models.reading_order import layout_label_role, normalize_layout_label
47
+
48
+ return layout_label_role(label) == "float" and normalize_layout_label(label) != "table"
49
+
50
+
51
+ def is_picture_region(region: "LayoutElement") -> bool:
52
+ """Check whether a layout region is a figure
53
+
54
+ Args:
55
+ region: the layout region
56
+
57
+ Returns:
58
+ True for a figure region
59
+ """
60
+ return is_picture_label(getattr(region, "type", None))
61
+
62
+
63
+ def picture_regions(page: "Page") -> list["LayoutElement"]:
64
+ """Return the figure regions of a page, without those nested in a larger figure
65
+
66
+ Args:
67
+ page: the page
68
+
69
+ Returns:
70
+ the figure regions, in detection order
71
+ """
72
+ from doctr.models.reading_order.base import _box_areas, _pairwise_overlaps, _to_boxes
73
+
74
+ regions = [region for region in (getattr(page, "layout", None) or []) if is_picture_region(region)]
75
+ if len(regions) < 2:
76
+ return regions
77
+ boxes = _to_boxes([region.geometry for region in regions])
78
+ inter_w, inter_h = _pairwise_overlaps(boxes, boxes)
79
+ areas = _box_areas(boxes)
80
+ inside = inter_w * inter_h >= 0.5 * areas[:, None]
81
+ # A region is nested when half of it lies in a larger region (or in an earlier one of the same area)
82
+ rank = np.empty(len(regions), dtype=int)
83
+ rank[np.argsort(-areas, kind="stable")] = np.arange(len(regions))
84
+ nested = (inside & (rank[None, :] < rank[:, None])).any(axis=1)
85
+ return [region for region, skip in zip(regions, nested) if not skip]
86
+
87
+
88
+ def _check_padding(padding: float) -> None:
89
+ if not padding >= 0:
90
+ raise ValueError(f"the padding should be a non-negative relative margin, got {padding}")
91
+
92
+
93
+ def _check_quality(quality: int) -> None:
94
+ if not 0 <= quality <= 100:
95
+ raise ValueError(f"the encoding quality should be between 0 and 100, got {quality}")
96
+
97
+
98
+ def _normalize_path_prefix(path_prefix: "str | os.PathLike[str]") -> str:
99
+ """Convert a path prefix to a directory prefix with forward slashes, valid in any link"""
100
+ prefix = os.fspath(path_prefix).replace("\\", "/")
101
+ if prefix and not prefix.endswith("/"):
102
+ prefix += "/"
103
+ return prefix
104
+
105
+
106
+ def _pad_geometry(points: np.ndarray, padding: float) -> np.ndarray:
107
+ """Grow a geometry around its center by a relative margin, clipped to the page"""
108
+ if padding == 0:
109
+ return points
110
+ center = points.mean(axis=0, keepdims=True)
111
+ return np.clip(center + (points - center) * (1 + 2 * padding), 0, 1)
112
+
113
+
114
+ def crop_layout_region(
115
+ page_img: np.ndarray | None,
116
+ geometry: Any,
117
+ padding: float = 0.0,
118
+ ) -> np.ndarray | None:
119
+ """Crop a layout region out of its page image, de-rotating rotated regions
120
+
121
+ Args:
122
+ page_img: the page image, None or empty when the page has no pixels
123
+ geometry: the relative geometry of the region, a straight box or a (4, 2) polygon
124
+ padding: relative margin added on each side
125
+
126
+ Returns:
127
+ the crop, or None without pixels or for a region smaller than 2x2 pixels
128
+ """
129
+ _check_padding(padding)
130
+ if page_img is None or page_img.size == 0:
131
+ return None
132
+ points = np.asarray(geometry, dtype=np.float32).reshape(-1, 2)
133
+ if points.shape[0] not in (2, 4):
134
+ return None
135
+ points = _pad_geometry(points, padding)
136
+ if points.shape[0] == 2: # straight box
137
+ box = np.array(
138
+ [[points[:, 0].min(), points[:, 1].min(), points[:, 0].max(), points[:, 1].max()]], dtype=np.float32
139
+ )
140
+ crops = extract_crops(page_img, box)
141
+ else: # rotated polygon
142
+ crops = extract_rcrops(page_img, points[None, ...].astype(np.float32))
143
+ if len(crops) == 0 or crops[0].size == 0 or min(crops[0].shape[:2]) < 2:
144
+ return None
145
+ return crops[0]
146
+
147
+
148
+ def encode_crop(crop: np.ndarray, image_format: str = "png", quality: int = 95) -> bytes:
149
+ """Encode an RGB(A) crop into an image file format
150
+
151
+ Args:
152
+ crop: the crop to encode, in np.uint8 or as floats in [0, 1]
153
+ image_format: one of 'png', 'jpg', 'jpeg' or 'webp'
154
+ quality: quality of the lossy formats, between 0 and 100
155
+
156
+ Returns:
157
+ the encoded image
158
+ """
159
+ if image_format not in IMAGE_FORMATS:
160
+ raise ValueError(f"unsupported image format '{image_format}', should be one of {list(IMAGE_FORMATS)}")
161
+ _check_quality(quality)
162
+ extension = ".jpg" if image_format in ("jpg", "jpeg") else f".{image_format}"
163
+ params: list[int] = []
164
+ if extension == ".jpg":
165
+ params = [int(cv2.IMWRITE_JPEG_QUALITY), int(quality)]
166
+ elif extension == ".webp":
167
+ params = [int(cv2.IMWRITE_WEBP_QUALITY), int(quality)]
168
+ array = crop
169
+ if np.issubdtype(array.dtype, np.floating):
170
+ # Float pages hold values in [0, 1] (like the predictors expect), the image formats need 8-bit values
171
+ array = (array * 255).round().clip(0, 255).astype(np.uint8)
172
+ # docTR pages are RGB, OpenCV expects BGR
173
+ if array.ndim == 3 and array.shape[2] == 3:
174
+ array = cv2.cvtColor(array, cv2.COLOR_RGB2BGR)
175
+ elif array.ndim == 3 and array.shape[2] == 4:
176
+ array = cv2.cvtColor(array, cv2.COLOR_RGBA2BGRA)
177
+ success, buffer = cv2.imencode(extension, array, params)
178
+ if not success: # pragma: no cover
179
+ raise RuntimeError(f"failed to encode a figure crop as '{image_format}'")
180
+ return buffer.tobytes()
181
+
182
+
183
+ class FigureEncoder:
184
+ """Render the figures detected by the layout model in the Markdown, AsciiDoc and HTML exports
185
+
186
+ * ``none``: no figures
187
+ * ``placeholder``: a comment marks each figure
188
+ * ``embedded``: each crop is inlined as a base64 data URI
189
+ * ``referenced``: each crop is written to ``image_dir`` and linked by its relative path
190
+
191
+ With their pixels ('embedded' or 'referenced'), the text recognized inside the figures is left out of the export.
192
+ Written files are named after the figure position and content, e.g. ``page1_figure2-3fa2b1c9.png``.
193
+
194
+ >>> from doctr.io import FigureEncoder
195
+ >>> markdown = page.export_as_markdown(images=FigureEncoder("referenced", image_dir="assets"))
196
+
197
+ Args:
198
+ mode: one of 'none', 'placeholder', 'embedded' or 'referenced'
199
+ image_dir: directory the crops are written to (required in 'referenced' mode)
200
+ path_prefix: location of ``image_dir`` relative to the export (``image_dir`` by default)
201
+ image_format: one of 'png', 'jpg', 'jpeg' or 'webp'
202
+ quality: quality of the lossy formats, between 0 and 100
203
+ padding: relative margin added around each region
204
+ """
205
+
206
+ def __init__(
207
+ self,
208
+ mode: str = "placeholder",
209
+ image_dir: str | Path | None = None,
210
+ path_prefix: "str | os.PathLike[str] | None" = None,
211
+ image_format: str = "png",
212
+ quality: int = 95,
213
+ padding: float = 0.0,
214
+ ) -> None:
215
+ if mode not in IMAGE_MODES:
216
+ raise ValueError(f"unsupported image mode '{mode}', should be one of {list(IMAGE_MODES)}")
217
+ if image_format not in IMAGE_FORMATS:
218
+ raise ValueError(f"unsupported image format '{image_format}', should be one of {list(IMAGE_FORMATS)}")
219
+ if mode == "referenced" and image_dir is None:
220
+ raise ValueError("an 'image_dir' is required to export the figures in 'referenced' mode")
221
+ _check_quality(quality)
222
+ _check_padding(padding)
223
+ self.mode = mode
224
+ self.image_dir = Path(image_dir) if image_dir is not None else None
225
+ if path_prefix is None:
226
+ path_prefix = image_dir if image_dir is not None else ""
227
+ self.path_prefix = _normalize_path_prefix(path_prefix)
228
+ self.image_format = image_format
229
+ self.quality = quality
230
+ self.padding = padding
231
+ # Files written in 'referenced' mode
232
+ self.written: list[Path] = []
233
+ # Encoded sources per page and region id, with weak keys so the cache does not keep the pages alive
234
+ self._sources: "weakref.WeakKeyDictionary[Page, dict[int, tuple[weakref.ref[LayoutElement], str | None]]]" = (
235
+ weakref.WeakKeyDictionary()
236
+ )
237
+
238
+ @classmethod
239
+ def resolve(cls, images: "str | FigureEncoder | None") -> "FigureEncoder":
240
+ """Build an encoder from the `images` argument of an export method
241
+
242
+ Args:
243
+ images: an image mode, an encoder, or None (same as 'none')
244
+
245
+ Returns:
246
+ the encoder
247
+ """
248
+ if isinstance(images, FigureEncoder):
249
+ return images
250
+ if images == "referenced":
251
+ raise ValueError(
252
+ "the 'referenced' mode writes the figures to a directory, pass a configured encoder instead: "
253
+ "images=FigureEncoder('referenced', image_dir='assets')"
254
+ )
255
+ return cls(mode="none" if images is None else images)
256
+
257
+ @property
258
+ def enabled(self) -> bool:
259
+ """Whether the figures appear in the export"""
260
+ return self.mode != "none"
261
+
262
+ @property
263
+ def materializes(self) -> bool:
264
+ """Whether the figures are exported with their pixels"""
265
+ return self.mode in ("embedded", "referenced")
266
+
267
+ def source(self, page: "Page", region: "LayoutElement", index: int) -> str | None:
268
+ """Return the image source of a figure, encoded (and written) on first use
269
+
270
+ Args:
271
+ page: the page of the figure
272
+ region: the figure region
273
+ index: 1-based index of the figure on the page, used in the file name
274
+
275
+ Returns:
276
+ a data URI or a relative path, None without pixels
277
+ """
278
+ if not self.materializes:
279
+ return None
280
+ cache = self._sources.setdefault(page, {})
281
+ cached = cache.get(id(region))
282
+ # Ids can be recycled: check that the cached one still denotes this region
283
+ if cached is not None and cached[0]() is region:
284
+ return cached[1]
285
+ source = self._encode(page, region, index)
286
+ cache[id(region)] = (weakref.ref(region), source)
287
+ return source
288
+
289
+ def _encode(self, page: "Page", region: "LayoutElement", index: int) -> str | None:
290
+ """Crop, encode and, in 'referenced' mode, write a figure"""
291
+ crop = crop_layout_region(getattr(page, "page", None), region.geometry, self.padding)
292
+ if crop is None:
293
+ return None
294
+ payload = encode_crop(crop, self.image_format, self.quality)
295
+ mime = "jpeg" if self.image_format in ("jpg", "jpeg") else self.image_format
296
+ if self.mode == "embedded":
297
+ return f"data:image/{mime};base64,{b64encode(payload).decode('ascii')}"
298
+ extension = "jpg" if mime == "jpeg" else mime
299
+ digest = hashlib.sha256(payload).hexdigest()[:8]
300
+ name = f"page{getattr(page, 'page_idx', 0) + 1}_figure{index}-{digest}.{extension}"
301
+ assert self.image_dir is not None # set in 'referenced' mode
302
+ self.image_dir.mkdir(parents=True, exist_ok=True)
303
+ path = self.image_dir / name
304
+ path.write_bytes(payload)
305
+ if path not in self.written:
306
+ self.written.append(path)
307
+ return quote(f"{self.path_prefix}{name}", safe="/:")
308
+
309
+ def __repr__(self) -> str:
310
+ return (
311
+ f"{self.__class__.__name__}(mode='{self.mode}', image_dir={self.image_dir}, "
312
+ f"image_format='{self.image_format}')"
313
+ )
doctr/io/image/base.py CHANGED
@@ -3,16 +3,59 @@
3
3
  # This program is licensed under the Apache License 2.0.
4
4
  # See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
5
5
 
6
+ from io import BytesIO
6
7
  from pathlib import Path
7
8
 
8
9
  import cv2
9
10
  import numpy as np
11
+ from PIL import Image, ImageOps
10
12
 
11
13
  from doctr.utils.common_types import AbstractFile
12
14
 
13
15
  __all__ = ["read_img_as_numpy"]
14
16
 
15
17
 
18
+ def _pil_to_rgb_array(pil_img: Image.Image) -> np.ndarray:
19
+ """Convert a PIL image to an RGB array, with its EXIF orientation applied (like `cv2.imdecode` does)
20
+ and transparent pixels placed on a white background
21
+
22
+ Args:
23
+ pil_img: a PIL image
24
+
25
+ Returns:
26
+ the image as a writable numpy array of shape H x W x 3 in np.uint8
27
+ """
28
+ has_transparency = pil_img.has_transparency_data
29
+ ImageOps.exif_transpose(pil_img, in_place=True)
30
+ if pil_img.mode.startswith("I;16"):
31
+ # Converting a 16-bit image to RGB clips its values to 255: scale them to 8 bits like `cv2.imdecode` does
32
+ pil_img = Image.fromarray((np.asarray(pil_img) >> 8).astype(np.uint8))
33
+ if not has_transparency:
34
+ return np.array(pil_img.convert("RGB"))
35
+ rgba = np.asarray(pil_img if pil_img.mode == "RGBA" else pil_img.convert("RGBA"))
36
+ rgb = cv2.cvtColor(rgba, cv2.COLOR_RGBA2RGB)
37
+ alpha = rgba[..., 3]
38
+ # Fully opaque images (e.g. screenshots) need no compositing
39
+ if alpha.min() == 255:
40
+ return rgb
41
+ # Dropping the alpha channel would reveal the color stored under the transparent pixels (often black),
42
+ # so blend with white in place: 255 - (255 - rgb) * alpha / 255
43
+ cv2.bitwise_not(rgb, dst=rgb)
44
+ cv2.multiply(rgb, cv2.cvtColor(np.ascontiguousarray(alpha), cv2.COLOR_GRAY2RGB), dst=rgb, scale=1 / 255)
45
+ return cv2.bitwise_not(rgb, dst=rgb)
46
+
47
+
48
+ def _decode_transparent_img(content: bytes) -> np.ndarray | None:
49
+ """Decode an image with transparency over a white background, in RGB order (None if it has no transparency)"""
50
+ try:
51
+ with Image.open(BytesIO(content)) as pil_img:
52
+ if not pil_img.has_transparency_data:
53
+ return None
54
+ return _pil_to_rgb_array(pil_img)
55
+ except (OSError, ValueError, Image.DecompressionBombError): # left to OpenCV
56
+ return None
57
+
58
+
16
59
  def read_img_as_numpy(
17
60
  file: AbstractFile,
18
61
  output_size: tuple[int, int] | None = None,
@@ -29,25 +72,29 @@ def read_img_as_numpy(
29
72
  rgb_output: whether the output ndarray channel order should be RGB instead of BGR.
30
73
 
31
74
  Returns:
32
- the page decoded as numpy ndarray of shape H x W x 3
75
+ the page decoded as numpy ndarray of shape H x W x 3, transparent images are placed on a white background
33
76
  """
34
77
  if isinstance(file, (str, Path)):
35
78
  if not Path(file).is_file():
36
79
  raise FileNotFoundError(f"unable to access {file}")
37
- img = cv2.imread(str(file), cv2.IMREAD_COLOR)
80
+ content = Path(file).read_bytes()
38
81
  elif isinstance(file, bytes):
39
- _file: np.ndarray = np.frombuffer(file, np.uint8)
40
- img = cv2.imdecode(_file, cv2.IMREAD_COLOR)
82
+ content = file
41
83
  else:
42
84
  raise TypeError("unsupported object type for argument 'file'")
43
85
 
86
+ img = _decode_transparent_img(content)
87
+ is_rgb = img is not None
88
+ if img is None:
89
+ img = cv2.imdecode(np.frombuffer(content, np.uint8), cv2.IMREAD_COLOR)
90
+
44
91
  # Validity check
45
92
  if img is None:
46
93
  raise ValueError("unable to read file.")
47
94
  # Resizing
48
95
  if isinstance(output_size, tuple):
49
96
  img = cv2.resize(img, output_size[::-1], interpolation=cv2.INTER_LINEAR)
50
- # Switch the channel order
51
- if rgb_output:
52
- img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
97
+ # Switch the channel order (OpenCV decodes as BGR, Pillow as RGB)
98
+ if rgb_output != is_rgb:
99
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB if rgb_output else cv2.COLOR_RGB2BGR)
53
100
  return img
doctr/io/image/pytorch.py CHANGED
@@ -12,6 +12,8 @@ from torchvision.transforms.functional import to_tensor
12
12
 
13
13
  from doctr.utils.common_types import AbstractPath
14
14
 
15
+ from .base import _pil_to_rgb_array
16
+
15
17
  __all__ = ["tensor_from_pil", "read_img_as_tensor", "decode_img_as_tensor", "tensor_from_numpy", "get_img_shape"]
16
18
 
17
19
 
@@ -47,7 +49,8 @@ def read_img_as_tensor(img_path: AbstractPath, dtype: torch.dtype = torch.float3
47
49
  raise ValueError("insupported value for dtype")
48
50
 
49
51
  with Image.open(img_path, mode="r") as pil_img:
50
- return tensor_from_pil(pil_img.convert("RGB"), dtype)
52
+ # Apply the EXIF orientation and place transparent pixels on white, like `read_img_as_numpy`
53
+ return tensor_from_numpy(_pil_to_rgb_array(pil_img), dtype)
51
54
 
52
55
 
53
56
  def decode_img_as_tensor(img_content: bytes, dtype: torch.dtype = torch.float32) -> torch.Tensor:
@@ -64,26 +67,31 @@ def decode_img_as_tensor(img_content: bytes, dtype: torch.dtype = torch.float32)
64
67
  raise ValueError("insupported value for dtype")
65
68
 
66
69
  with Image.open(BytesIO(img_content), mode="r") as pil_img:
67
- return tensor_from_pil(pil_img.convert("RGB"), dtype)
70
+ return tensor_from_numpy(_pil_to_rgb_array(pil_img), dtype)
68
71
 
69
72
 
70
73
  def tensor_from_numpy(npy_img: np.ndarray, dtype: torch.dtype = torch.float32) -> torch.Tensor:
71
74
  """Read an image file as a PyTorch tensor
72
75
 
73
76
  Args:
74
- npy_img: image encoded as a numpy array of shape (H, W, C) in np.uint8
77
+ npy_img: image encoded as a numpy array of shape (H, W) or (H, W, C) in np.uint8
75
78
  dtype: the desired data type of the output tensor. If it is float-related, values will be divided by 255.
76
79
 
77
80
  Returns:
78
- same image as a tensor of shape (C, H, W)
81
+ same image as a tensor of shape (C, H, W), with C = 1 for a grayscale image
79
82
  """
80
83
  if dtype not in (torch.uint8, torch.float16, torch.float32):
81
84
  raise ValueError("insupported value for dtype")
82
85
 
86
+ # torch.from_numpy requires a writable buffer without negative strides (e.g. a flipped or rotated view)
87
+ if not npy_img.flags.writeable or any(stride < 0 for stride in npy_img.strides):
88
+ npy_img = npy_img.copy()
89
+
83
90
  if dtype == torch.float32:
84
91
  img = to_tensor(npy_img)
85
92
  else:
86
- img = torch.from_numpy(npy_img)
93
+ # A grayscale image gets a channel axis, like `to_tensor` gives it for float32
94
+ img = torch.from_numpy(npy_img[..., None] if npy_img.ndim == 2 else npy_img)
87
95
  # put it from HWC to CHW format
88
96
  img = img.permute((2, 0, 1)).contiguous()
89
97
  if dtype == torch.float16:
doctr/io/pdf.py CHANGED
@@ -6,10 +6,11 @@
6
6
  from typing import Any
7
7
 
8
8
  import numpy as np
9
- import pypdfium2 as pdfium
10
9
 
11
10
  from doctr.utils.common_types import AbstractFile
12
11
 
12
+ from .sources import PDFSource
13
+
13
14
  __all__ = ["read_pdf"]
14
15
 
15
16
 
@@ -35,9 +36,9 @@ def read_pdf(
35
36
  Returns:
36
37
  the list of pages decoded as numpy ndarray of shape H x W x C
37
38
  """
38
- # Rasterise pages to numpy ndarrays with pypdfium2
39
- pdf = pdfium.PdfDocument(file, password=password)
39
+ # Rasterise pages to numpy ndarrays with pypdfium2 (use `PDFSource` directly to render them on demand)
40
+ source = PDFSource(file, scale=scale, rgb_mode=rgb_mode, password=password, **kwargs)
40
41
  try:
41
- return [page.render(scale=scale, rev_byteorder=rgb_mode, **kwargs).to_numpy() for page in pdf]
42
+ return list(source)
42
43
  finally:
43
- pdf.close()
44
+ source.close()