python-doctr 1.1.0__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/main.py +186 -23
- doctr/datasets/detection.py +12 -2
- doctr/datasets/generator/base.py +118 -35
- doctr/datasets/generator/pytorch.py +1 -1
- doctr/datasets/ic03.py +6 -5
- doctr/datasets/layout.py +7 -1
- doctr/datasets/recognition.py +3 -3
- doctr/datasets/svt.py +7 -6
- doctr/datasets/utils.py +100 -26
- doctr/datasets/vocabs.py +320 -150
- doctr/io/__init__.py +2 -0
- doctr/io/elements.py +138 -20
- doctr/io/exporters.py +848 -208
- doctr/io/figures.py +313 -0
- doctr/io/image/base.py +54 -8
- doctr/io/image/pytorch.py +14 -8
- doctr/io/pdf.py +6 -5
- doctr/io/reader.py +268 -18
- doctr/io/sources.py +636 -0
- doctr/models/__init__.py +1 -0
- doctr/models/_utils.py +150 -5
- doctr/models/builder.py +316 -334
- doctr/models/classification/__init__.py +1 -0
- doctr/models/classification/hgnetv2/__init__.py +1 -0
- doctr/models/classification/hgnetv2/pytorch.py +352 -0
- doctr/models/classification/predictor/pytorch.py +28 -0
- doctr/models/classification/zoo.py +11 -2
- doctr/models/detection/core.py +1 -2
- doctr/models/detection/differentiable_binarization/base.py +17 -5
- doctr/models/detection/differentiable_binarization/pytorch.py +7 -1
- doctr/models/detection/fast/base.py +17 -5
- doctr/models/detection/fast/pytorch.py +21 -8
- doctr/models/detection/linknet/base.py +17 -5
- doctr/models/detection/linknet/pytorch.py +7 -0
- doctr/models/detection/predictor/pytorch.py +40 -0
- doctr/models/detection/zoo.py +4 -0
- doctr/models/factory/hub.py +5 -2
- 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 +7 -0
- doctr/models/kie_predictor/pytorch.py +47 -6
- doctr/models/layout/lw_detr/pytorch.py +150 -93
- doctr/models/layout/predictor/pytorch.py +32 -0
- doctr/models/layout/zoo.py +4 -0
- doctr/models/modules/transformer/pytorch.py +151 -31
- doctr/models/predictor/base.py +283 -7
- doctr/models/predictor/pytorch.py +53 -98
- doctr/models/preprocessor/pytorch.py +13 -11
- doctr/models/reading_order/base.py +720 -260
- doctr/models/recognition/core.py +14 -1
- doctr/models/recognition/crnn/pytorch.py +37 -11
- doctr/models/recognition/master/base.py +4 -1
- doctr/models/recognition/master/pytorch.py +83 -20
- doctr/models/recognition/parseq/base.py +4 -1
- doctr/models/recognition/parseq/pytorch.py +123 -22
- doctr/models/recognition/predictor/_utils.py +131 -14
- doctr/models/recognition/predictor/pytorch.py +67 -11
- doctr/models/recognition/sar/pytorch.py +20 -6
- doctr/models/recognition/utils.py +75 -43
- doctr/models/recognition/viptr/pytorch.py +37 -11
- doctr/models/recognition/vitstr/base.py +4 -1
- doctr/models/recognition/vitstr/pytorch.py +7 -3
- doctr/models/recognition/zoo.py +31 -3
- doctr/models/table_structure/grid.py +430 -0
- doctr/models/table_structure/predictor/pytorch.py +152 -1
- doctr/models/table_structure/tablecenternet/base.py +206 -16
- doctr/models/table_structure/tablecenternet/pytorch.py +8 -5
- doctr/models/table_structure/zoo.py +5 -0
- doctr/models/utils/pytorch.py +73 -16
- doctr/models/zoo.py +53 -4
- doctr/transforms/functional/base.py +6 -0
- doctr/transforms/functional/pytorch.py +134 -6
- doctr/transforms/modules/base.py +17 -3
- doctr/transforms/modules/pytorch.py +185 -4
- doctr/utils/data.py +20 -9
- doctr/utils/fonts.py +17 -9
- doctr/utils/geometry.py +36 -14
- doctr/utils/metrics.py +143 -13
- doctr/utils/multithreading.py +122 -2
- doctr/utils/visualization.py +11 -7
- doctr/version.py +1 -1
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/METADATA +54 -224
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/RECORD +93 -81
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/entry_points.txt +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
doctr/datasets/ic03.py
CHANGED
|
@@ -85,8 +85,9 @@ class IC03(VisionDataset):
|
|
|
85
85
|
name, _resolution, rectangles = image
|
|
86
86
|
|
|
87
87
|
# File existence check
|
|
88
|
-
|
|
89
|
-
|
|
88
|
+
img_name = name.text
|
|
89
|
+
if not img_name or not os.path.exists(os.path.join(tmp_root, img_name)):
|
|
90
|
+
raise FileNotFoundError(f"unable to locate {os.path.join(tmp_root, img_name or '')}")
|
|
90
91
|
|
|
91
92
|
if use_polygons:
|
|
92
93
|
# (x, y) coordinates of top left, top right, bottom right, bottom left corners
|
|
@@ -121,14 +122,14 @@ class IC03(VisionDataset):
|
|
|
121
122
|
labels = [lab.text for rect in rectangles for lab in rect if lab.text]
|
|
122
123
|
|
|
123
124
|
if recognition_task:
|
|
124
|
-
crops = crop_bboxes_from_image(img_path=os.path.join(tmp_root,
|
|
125
|
+
crops = crop_bboxes_from_image(img_path=os.path.join(tmp_root, img_name), geoms=boxes)
|
|
125
126
|
for crop, label in zip(crops, labels):
|
|
126
127
|
if crop.shape[0] > 0 and crop.shape[1] > 0 and len(label) > 0 and " " not in label:
|
|
127
128
|
self.data.append((crop, label))
|
|
128
129
|
elif detection_task:
|
|
129
|
-
self.data.append((
|
|
130
|
+
self.data.append((img_name, boxes))
|
|
130
131
|
else:
|
|
131
|
-
self.data.append((
|
|
132
|
+
self.data.append((img_name, dict(boxes=boxes, labels=labels)))
|
|
132
133
|
|
|
133
134
|
self.root = tmp_root
|
|
134
135
|
|
doctr/datasets/layout.py
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import json
|
|
7
7
|
import os
|
|
8
|
+
from functools import partial
|
|
8
9
|
from typing import Any
|
|
9
10
|
|
|
10
11
|
import numpy as np
|
|
@@ -90,6 +91,9 @@ class LayoutDataset(AbstractDataset):
|
|
|
90
91
|
),
|
|
91
92
|
))
|
|
92
93
|
|
|
94
|
+
# Expose every class in every sample so the class -> channel mapping never shifts
|
|
95
|
+
self._pre_transforms = partial(pre_transform_multiclass, class_names=self.class_names)
|
|
96
|
+
|
|
93
97
|
def format_polygons(
|
|
94
98
|
self,
|
|
95
99
|
polygons: list,
|
|
@@ -111,7 +115,9 @@ class LayoutDataset(AbstractDataset):
|
|
|
111
115
|
"""
|
|
112
116
|
self._class_names += class_names
|
|
113
117
|
|
|
114
|
-
_polygons: np.ndarray =
|
|
118
|
+
_polygons: np.ndarray = (
|
|
119
|
+
np.asarray(polygons, dtype=np_dtype) if len(polygons) else np.zeros((0, 4, 2), dtype=np_dtype)
|
|
120
|
+
) # an image without any region is a valid (all-background) sample
|
|
115
121
|
if _polygons.ndim != 3 or _polygons.shape[1:] != (4, 2):
|
|
116
122
|
raise ValueError(f"polygons are expected to have shape (N, 4, 2), got {_polygons.shape}")
|
|
117
123
|
geoms = _polygons if use_polygons else np.concatenate((_polygons.min(axis=1), _polygons.max(axis=1)), axis=1)
|
doctr/datasets/recognition.py
CHANGED
|
@@ -47,10 +47,10 @@ class RecognitionDataset(AbstractDataset):
|
|
|
47
47
|
self.data.append((img_name, label))
|
|
48
48
|
|
|
49
49
|
def merge_dataset(self, ds: AbstractDataset) -> None:
|
|
50
|
-
# Update data with new root for self
|
|
51
|
-
self.data = [(str(Path(self.root).joinpath(img_path)), label) for img_path, label in self.data]
|
|
50
|
+
# Update data with new root for self (absolute paths, a relative one would be read from the new root)
|
|
51
|
+
self.data = [(str(Path(self.root).absolute().joinpath(img_path)), label) for img_path, label in self.data]
|
|
52
52
|
# Define new root
|
|
53
53
|
self.root = Path("/")
|
|
54
54
|
# Merge with ds data
|
|
55
55
|
for img_path, label in ds.data:
|
|
56
|
-
self.data.append((str(Path(ds.root).joinpath(img_path)), label))
|
|
56
|
+
self.data.append((str(Path(ds.root).absolute().joinpath(img_path)), label))
|
doctr/datasets/svt.py
CHANGED
|
@@ -78,8 +78,9 @@ class SVT(VisionDataset):
|
|
|
78
78
|
name, _, _, _resolution, rectangles = image
|
|
79
79
|
|
|
80
80
|
# File existence check
|
|
81
|
-
|
|
82
|
-
|
|
81
|
+
img_name = name.text
|
|
82
|
+
if not img_name or not os.path.exists(os.path.join(tmp_root, img_name)):
|
|
83
|
+
raise FileNotFoundError(f"unable to locate {os.path.join(tmp_root, img_name or '')}")
|
|
83
84
|
|
|
84
85
|
if use_polygons:
|
|
85
86
|
# (x, y) coordinates of top left, top right, bottom right, bottom left corners
|
|
@@ -112,14 +113,14 @@ class SVT(VisionDataset):
|
|
|
112
113
|
labels = [lab.text for rect in rectangles for lab in rect]
|
|
113
114
|
|
|
114
115
|
if recognition_task:
|
|
115
|
-
crops = crop_bboxes_from_image(img_path=os.path.join(tmp_root,
|
|
116
|
+
crops = crop_bboxes_from_image(img_path=os.path.join(tmp_root, img_name), geoms=boxes)
|
|
116
117
|
for crop, label in zip(crops, labels):
|
|
117
|
-
if crop.shape[0] > 0 and crop.shape[1] > 0 and
|
|
118
|
+
if crop.shape[0] > 0 and crop.shape[1] > 0 and label and " " not in label:
|
|
118
119
|
self.data.append((crop, label))
|
|
119
120
|
elif detection_task:
|
|
120
|
-
self.data.append((
|
|
121
|
+
self.data.append((img_name, boxes))
|
|
121
122
|
else:
|
|
122
|
-
self.data.append((
|
|
123
|
+
self.data.append((img_name, dict(boxes=boxes, labels=labels)))
|
|
123
124
|
|
|
124
125
|
self.root = tmp_root
|
|
125
126
|
|
doctr/datasets/utils.py
CHANGED
|
@@ -3,11 +3,12 @@
|
|
|
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
|
+
import re
|
|
6
7
|
import string
|
|
7
8
|
import unicodedata
|
|
8
9
|
from collections.abc import Sequence
|
|
9
10
|
from collections.abc import Sequence as SequenceType
|
|
10
|
-
from functools import lru_cache
|
|
11
|
+
from functools import lru_cache
|
|
11
12
|
from pathlib import Path
|
|
12
13
|
from typing import Any, TypeVar
|
|
13
14
|
|
|
@@ -21,6 +22,8 @@ from .vocabs import VOCABS
|
|
|
21
22
|
|
|
22
23
|
__all__ = [
|
|
23
24
|
"translate",
|
|
25
|
+
"tokenize_latex",
|
|
26
|
+
"normalize_latex",
|
|
24
27
|
"encode_string",
|
|
25
28
|
"decode_sequence",
|
|
26
29
|
"encode_sequences",
|
|
@@ -66,62 +69,121 @@ def translate(
|
|
|
66
69
|
return translated
|
|
67
70
|
|
|
68
71
|
|
|
72
|
+
# A LaTeX token: an environment delimiter (e.g. \begin{array}), a command (e.g. \frac, \operatorname*), a control
|
|
73
|
+
# symbol (e.g. \{, \, or \\) or any other non-whitespace character
|
|
74
|
+
_LATEX_TOKEN = re.compile(r"\\(?:begin|end)\s*\{[a-zA-Z]+\*?\}|\\[a-zA-Z]+\*?|\\.|\S", re.DOTALL)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def tokenize_latex(latex: str) -> list[str]:
|
|
78
|
+
r"""Split a LaTeX string into tokens: commands, environment delimiters, control symbols and single characters
|
|
79
|
+
|
|
80
|
+
>>> from doctr.datasets import tokenize_latex
|
|
81
|
+
>>> tokenize_latex(r"\frac{a}{b^2}")
|
|
82
|
+
['\\frac', '{', 'a', '}', '{', 'b', '^', '2', '}']
|
|
83
|
+
|
|
84
|
+
The whitespaces are not part of the tokens (a control space `\ ` is tokenized as `\space`, which renders the same):
|
|
85
|
+
tokenizing a string and joining the tokens with spaces gives a normalized string which tokenizes into the same
|
|
86
|
+
tokens.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
latex: the LaTeX string to tokenize
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
the list of tokens
|
|
93
|
+
"""
|
|
94
|
+
tokens = []
|
|
95
|
+
for tok in _LATEX_TOKEN.findall(latex):
|
|
96
|
+
if tok.startswith(("\\begin", "\\end")):
|
|
97
|
+
# Drop the whitespaces between an environment delimiter and its name (e.g. "\begin {array}")
|
|
98
|
+
tok = re.sub(r"\s+", "", tok)
|
|
99
|
+
elif len(tok) == 2 and tok[1].isspace():
|
|
100
|
+
tok = "\\space"
|
|
101
|
+
tokens.append(tok)
|
|
102
|
+
return tokens
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def normalize_latex(latex: str) -> str:
|
|
106
|
+
r"""Normalize a LaTeX string into space-separated tokens (cf. :func:`tokenize_latex`)
|
|
107
|
+
|
|
108
|
+
>>> from doctr.datasets import normalize_latex
|
|
109
|
+
>>> normalize_latex(r"\frac{a}{b^2}")
|
|
110
|
+
'\\frac { a } { b ^ 2 }'
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
latex: the LaTeX string to normalize
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
the normalized string, rendering the same as the input
|
|
117
|
+
"""
|
|
118
|
+
return " ".join(tokenize_latex(latex))
|
|
119
|
+
|
|
120
|
+
|
|
69
121
|
@lru_cache(maxsize=32)
|
|
70
|
-
def _vocab_lookup_table(vocab: str) -> dict[str, int]:
|
|
71
|
-
"""Cached
|
|
72
|
-
return {
|
|
122
|
+
def _vocab_lookup_table(vocab: str | tuple[str, ...]) -> dict[str, int]:
|
|
123
|
+
"""Cached token -> index table for a vocab (the first occurrence of a duplicated token wins)"""
|
|
124
|
+
return {token: idx for idx, token in reversed(list(enumerate(vocab)))}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _split_tokens(input_string: str, vocab: str | Sequence[str]) -> list[str]:
|
|
128
|
+
"""Split a string into the units of a vocab: characters for a string vocab, whitespace-separated tokens for a
|
|
129
|
+
list of tokens"""
|
|
130
|
+
return list(input_string) if isinstance(vocab, str) else input_string.split()
|
|
73
131
|
|
|
74
132
|
|
|
75
133
|
def encode_string(
|
|
76
134
|
input_string: str,
|
|
77
|
-
vocab: str,
|
|
135
|
+
vocab: str | Sequence[str],
|
|
78
136
|
) -> list[int]:
|
|
79
137
|
"""Given a predefined mapping, encode the string to a sequence of numbers
|
|
80
138
|
|
|
81
139
|
Args:
|
|
82
140
|
input_string: string to encode
|
|
83
|
-
vocab: vocabulary
|
|
141
|
+
vocab: vocabulary, the encoding is given by the indexing of its units: a string of characters, or a list of
|
|
142
|
+
tokens (e.g. LaTeX commands), in which case the input string is split on whitespaces
|
|
84
143
|
|
|
85
144
|
Returns:
|
|
86
145
|
A list encoding the input_string
|
|
87
146
|
"""
|
|
88
|
-
table = _vocab_lookup_table(vocab)
|
|
147
|
+
table = _vocab_lookup_table(vocab if isinstance(vocab, str) else tuple(vocab))
|
|
148
|
+
tokens = _split_tokens(input_string, vocab)
|
|
89
149
|
try:
|
|
90
|
-
return [table[
|
|
150
|
+
return [table[token] for token in tokens]
|
|
91
151
|
except KeyError as e:
|
|
92
|
-
|
|
152
|
+
missing = [token for token in tokens if token not in table]
|
|
93
153
|
raise ValueError(
|
|
94
|
-
f"Some characters cannot be found in 'vocab': {set(
|
|
154
|
+
f"Some characters cannot be found in 'vocab': {set(missing)}.\n"
|
|
95
155
|
f"Please check the input string `{input_string}` and the vocabulary `{vocab}`"
|
|
96
156
|
) from e
|
|
97
157
|
|
|
98
158
|
|
|
99
159
|
def decode_sequence(
|
|
100
160
|
input_seq: np.ndarray | SequenceType[int],
|
|
101
|
-
mapping: str,
|
|
161
|
+
mapping: str | Sequence[str],
|
|
102
162
|
) -> str:
|
|
103
163
|
"""Given a predefined mapping, decode the sequence of numbers to a string
|
|
104
164
|
|
|
105
165
|
Args:
|
|
106
166
|
input_seq: array to decode
|
|
107
|
-
mapping: vocabulary
|
|
167
|
+
mapping: vocabulary, the encoding is given by the indexing of its units: a string of characters, or a list of
|
|
168
|
+
tokens, in which case the decoded tokens are joined with spaces
|
|
108
169
|
|
|
109
170
|
Returns:
|
|
110
171
|
A string, decoded from input_seq
|
|
111
172
|
"""
|
|
112
173
|
if not isinstance(input_seq, (Sequence, np.ndarray)):
|
|
113
174
|
raise TypeError("Invalid sequence type")
|
|
114
|
-
if isinstance(input_seq, np.ndarray) and (
|
|
115
|
-
|
|
116
|
-
)
|
|
117
|
-
|
|
175
|
+
if isinstance(input_seq, np.ndarray) and not np.issubdtype(input_seq.dtype, np.integer):
|
|
176
|
+
raise AssertionError("Input must be an array of int, with values between 0 and the mapping size")
|
|
177
|
+
# A negative index would silently wrap around to the end of the mapping (e.g. an EOS of -1 read as a char)
|
|
178
|
+
if len(input_seq) > 0 and (min(input_seq) < 0 or max(input_seq) >= len(mapping)):
|
|
179
|
+
raise AssertionError("Input must be an array of int, with values between 0 and the mapping size")
|
|
118
180
|
|
|
119
|
-
return "".join(map(mapping.__getitem__, input_seq))
|
|
181
|
+
return ("" if isinstance(mapping, str) else " ").join(map(mapping.__getitem__, input_seq))
|
|
120
182
|
|
|
121
183
|
|
|
122
184
|
def encode_sequences(
|
|
123
185
|
sequences: list[str],
|
|
124
|
-
vocab: str,
|
|
186
|
+
vocab: str | Sequence[str],
|
|
125
187
|
target_size: int | None = None,
|
|
126
188
|
eos: int = -1,
|
|
127
189
|
sos: int | None = None,
|
|
@@ -132,7 +194,8 @@ def encode_sequences(
|
|
|
132
194
|
|
|
133
195
|
Args:
|
|
134
196
|
sequences: the list of character sequences of size N
|
|
135
|
-
vocab: the ordered vocab to use for encoding
|
|
197
|
+
vocab: the ordered vocab to use for encoding: a string of characters, or a list of tokens (cf.
|
|
198
|
+
:func:`encode_string`)
|
|
136
199
|
target_size: maximum length of the encoded data
|
|
137
200
|
eos: encoding of End Of String
|
|
138
201
|
sos: optional encoding of Start Of String
|
|
@@ -145,9 +208,10 @@ def encode_sequences(
|
|
|
145
208
|
if 0 <= eos < len(vocab):
|
|
146
209
|
raise ValueError("argument 'eos' needs to be outside of vocab possible indices")
|
|
147
210
|
|
|
211
|
+
encoded_seqs = [encode_string(seq, vocab) for seq in sequences]
|
|
148
212
|
if not isinstance(target_size, int) or dynamic_seq_length:
|
|
149
|
-
# Maximum
|
|
150
|
-
max_length = max(len(
|
|
213
|
+
# Maximum sequence length (in vocab units) + EOS
|
|
214
|
+
max_length = max((len(seq) for seq in encoded_seqs), default=0) + 1
|
|
151
215
|
if isinstance(sos, int):
|
|
152
216
|
max_length += 1
|
|
153
217
|
if isinstance(pad, int):
|
|
@@ -165,7 +229,7 @@ def encode_sequences(
|
|
|
165
229
|
encoded_data: np.ndarray = np.full([len(sequences), target_size], default_symbol, dtype=np.int32)
|
|
166
230
|
|
|
167
231
|
# Encode the strings
|
|
168
|
-
for idx, seq in enumerate(
|
|
232
|
+
for idx, seq in enumerate(encoded_seqs):
|
|
169
233
|
if isinstance(pad, int): # add eos at the end of the sequence
|
|
170
234
|
seq.append(eos)
|
|
171
235
|
encoded_data[idx, : min(len(seq), target_size)] = seq[: min(len(seq), target_size)]
|
|
@@ -218,20 +282,30 @@ def crop_bboxes_from_image(img_path: str | Path, geoms: np.ndarray) -> list[np.n
|
|
|
218
282
|
raise ValueError("Invalid geometry format")
|
|
219
283
|
|
|
220
284
|
|
|
221
|
-
def pre_transform_multiclass(
|
|
285
|
+
def pre_transform_multiclass(
|
|
286
|
+
img, target: tuple[np.ndarray, list], class_names: list[str] | None = None
|
|
287
|
+
) -> tuple[np.ndarray, dict[str, np.ndarray]]:
|
|
222
288
|
"""Converts multiclass target to relative coordinates.
|
|
223
289
|
|
|
224
290
|
Args:
|
|
225
291
|
img: Image
|
|
226
292
|
target: tuple of target polygons and their classes names
|
|
293
|
+
class_names: if given, the returned dictionary contains exactly these classes, in this order.
|
|
294
|
+
Classes without any box in this sample map to an empty array. This keeps the class -> channel
|
|
295
|
+
mapping stable across samples, which the detection models rely on.
|
|
227
296
|
|
|
228
297
|
Returns:
|
|
229
298
|
Image and dictionary of boxes, with class names as keys
|
|
230
299
|
"""
|
|
231
300
|
boxes = convert_to_relative_coords(target[0], get_img_shape(img))
|
|
232
301
|
boxes_classes = target[1]
|
|
233
|
-
|
|
302
|
+
keys = list(class_names) if class_names is not None else sorted(set(boxes_classes))
|
|
303
|
+
boxes_dict: dict[str, list] = {k: [] for k in keys}
|
|
234
304
|
for k, poly in zip(boxes_classes, boxes):
|
|
305
|
+
if k not in boxes_dict:
|
|
306
|
+
raise ValueError(f"unknown class '{k}', expected one of {keys}")
|
|
235
307
|
boxes_dict[k].append(poly)
|
|
236
|
-
|
|
237
|
-
|
|
308
|
+
return img, {
|
|
309
|
+
k: np.stack(v, axis=0) if v else np.zeros((0, *boxes.shape[1:]), dtype=boxes.dtype)
|
|
310
|
+
for k, v in boxes_dict.items()
|
|
311
|
+
}
|