doc-preproc 0.1.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.
- doc_preproc/__init__.py +51 -0
- doc_preproc/diagnose.py +318 -0
- doc_preproc/geometry.py +134 -0
- doc_preproc/models.py +233 -0
- doc_preproc/preprocess.py +306 -0
- doc_preproc/py.typed +0 -0
- doc_preproc-0.1.0.dist-info/METADATA +83 -0
- doc_preproc-0.1.0.dist-info/RECORD +10 -0
- doc_preproc-0.1.0.dist-info/WHEEL +5 -0
- doc_preproc-0.1.0.dist-info/top_level.txt +1 -0
doc_preproc/__init__.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""doc-preproc: lightweight, non-destructive document image preprocessing."""
|
|
2
|
+
|
|
3
|
+
from .diagnose import (
|
|
4
|
+
compute_blur_score,
|
|
5
|
+
compute_contrast_score,
|
|
6
|
+
compute_illumination_unevenness,
|
|
7
|
+
diagnose,
|
|
8
|
+
estimate_char_height_px,
|
|
9
|
+
estimate_skew_angle,
|
|
10
|
+
)
|
|
11
|
+
from .geometry import AffineTransform2D
|
|
12
|
+
from .models import (
|
|
13
|
+
CropPlan,
|
|
14
|
+
GrayImage,
|
|
15
|
+
PreprocessConfig,
|
|
16
|
+
PreprocessResult,
|
|
17
|
+
ProfileName,
|
|
18
|
+
QualityReport,
|
|
19
|
+
)
|
|
20
|
+
from .preprocess import (
|
|
21
|
+
apply_crop_plan,
|
|
22
|
+
compute_crop_plan,
|
|
23
|
+
deskew_image,
|
|
24
|
+
normalize_illumination,
|
|
25
|
+
preprocess,
|
|
26
|
+
stretch_contrast,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"AffineTransform2D",
|
|
31
|
+
"CropPlan",
|
|
32
|
+
"GrayImage",
|
|
33
|
+
"PreprocessConfig",
|
|
34
|
+
"PreprocessResult",
|
|
35
|
+
"ProfileName",
|
|
36
|
+
"QualityReport",
|
|
37
|
+
"apply_crop_plan",
|
|
38
|
+
"compute_blur_score",
|
|
39
|
+
"compute_contrast_score",
|
|
40
|
+
"compute_crop_plan",
|
|
41
|
+
"compute_illumination_unevenness",
|
|
42
|
+
"deskew_image",
|
|
43
|
+
"diagnose",
|
|
44
|
+
"estimate_char_height_px",
|
|
45
|
+
"estimate_skew_angle",
|
|
46
|
+
"normalize_illumination",
|
|
47
|
+
"preprocess",
|
|
48
|
+
"stretch_contrast",
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
__version__ = "0.1.0"
|
doc_preproc/diagnose.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
"""Document image quality diagnosis metrics."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from typing import Any, Sequence
|
|
7
|
+
|
|
8
|
+
from .models import GrayImage, PreprocessConfig, QualityReport
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _percentile(sorted_vals: Sequence[float], q: float) -> float:
|
|
12
|
+
"""Compute linear-interpolated percentile from a pre-sorted sequence."""
|
|
13
|
+
n = len(sorted_vals)
|
|
14
|
+
if n == 0:
|
|
15
|
+
return 0.0
|
|
16
|
+
if n == 1:
|
|
17
|
+
return sorted_vals[0]
|
|
18
|
+
pos = q * (n - 1)
|
|
19
|
+
lo = int(math.floor(pos))
|
|
20
|
+
hi = min(lo + 1, n - 1)
|
|
21
|
+
frac = pos - lo
|
|
22
|
+
return sorted_vals[lo] * (1.0 - frac) + sorted_vals[hi] * frac
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _image_stats(gray: GrayImage) -> tuple[float, float, float, float, float, float]:
|
|
26
|
+
"""Return (mean, std, min_val, max_val, p5, p95) for pixel intensities."""
|
|
27
|
+
flat: list[float] = []
|
|
28
|
+
for row in gray.pixels:
|
|
29
|
+
flat.extend(row)
|
|
30
|
+
n = len(flat)
|
|
31
|
+
mean = sum(flat) / n
|
|
32
|
+
var = sum((v - mean) * (v - mean) for v in flat) / n
|
|
33
|
+
std = math.sqrt(var)
|
|
34
|
+
flat.sort()
|
|
35
|
+
return (
|
|
36
|
+
mean,
|
|
37
|
+
std,
|
|
38
|
+
flat[0],
|
|
39
|
+
flat[-1],
|
|
40
|
+
_percentile(flat, 0.05),
|
|
41
|
+
_percentile(flat, 0.95),
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def compute_blur_score(image: GrayImage | Any) -> float:
|
|
46
|
+
"""Estimate sharpness via variance of the discrete 2D Laplacian.
|
|
47
|
+
|
|
48
|
+
Higher values indicate sharper edges; values near zero indicate
|
|
49
|
+
severe blur or flat/featureless content.
|
|
50
|
+
"""
|
|
51
|
+
gray = GrayImage.from_any(image)
|
|
52
|
+
w, h = gray.width, gray.height
|
|
53
|
+
if w < 3 or h < 3:
|
|
54
|
+
return 0.0
|
|
55
|
+
|
|
56
|
+
pixels = gray.pixels
|
|
57
|
+
count = (w - 2) * (h - 2)
|
|
58
|
+
sum_l = 0.0
|
|
59
|
+
sum_l2 = 0.0
|
|
60
|
+
for y in range(1, h - 1):
|
|
61
|
+
row_prev = pixels[y - 1]
|
|
62
|
+
row_curr = pixels[y]
|
|
63
|
+
row_next = pixels[y + 1]
|
|
64
|
+
for x in range(1, w - 1):
|
|
65
|
+
lap = (
|
|
66
|
+
row_prev[x]
|
|
67
|
+
+ row_next[x]
|
|
68
|
+
+ row_curr[x - 1]
|
|
69
|
+
+ row_curr[x + 1]
|
|
70
|
+
- 4.0 * row_curr[x]
|
|
71
|
+
)
|
|
72
|
+
sum_l += lap
|
|
73
|
+
sum_l2 += lap * lap
|
|
74
|
+
|
|
75
|
+
mean_l = sum_l / count
|
|
76
|
+
var_l = (sum_l2 / count) - (mean_l * mean_l)
|
|
77
|
+
return max(0.0, var_l)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def compute_contrast_score(image: GrayImage | Any) -> float:
|
|
81
|
+
"""Compute contrast as the standard deviation of grayscale intensities."""
|
|
82
|
+
gray = GrayImage.from_any(image)
|
|
83
|
+
_, std, _, _, _, _ = _image_stats(gray)
|
|
84
|
+
return std
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def compute_illumination_unevenness(
|
|
88
|
+
image: GrayImage | Any,
|
|
89
|
+
grid_rows: int = 4,
|
|
90
|
+
grid_cols: int = 4,
|
|
91
|
+
) -> float:
|
|
92
|
+
"""Measure spatial illumination gradient across a grid of blocks.
|
|
93
|
+
|
|
94
|
+
Uses the 85th percentile inside each block as a robust local background
|
|
95
|
+
estimate so that text density differences do not masquerade as shadows.
|
|
96
|
+
Returns ``max(block_bg) - min(block_bg)``.
|
|
97
|
+
"""
|
|
98
|
+
gray = GrayImage.from_any(image)
|
|
99
|
+
w, h = gray.width, gray.height
|
|
100
|
+
rows = min(grid_rows, h)
|
|
101
|
+
cols = min(grid_cols, w)
|
|
102
|
+
if rows <= 1 and cols <= 1:
|
|
103
|
+
return 0.0
|
|
104
|
+
|
|
105
|
+
block_bgs: list[float] = []
|
|
106
|
+
pixels = gray.pixels
|
|
107
|
+
for r in range(rows):
|
|
108
|
+
y0 = (r * h) // rows
|
|
109
|
+
y1 = ((r + 1) * h) // rows
|
|
110
|
+
if y1 <= y0:
|
|
111
|
+
continue
|
|
112
|
+
for c in range(cols):
|
|
113
|
+
x0 = (c * w) // cols
|
|
114
|
+
x1 = ((c + 1) * w) // cols
|
|
115
|
+
if x1 <= x0:
|
|
116
|
+
continue
|
|
117
|
+
vals: list[float] = []
|
|
118
|
+
for y in range(y0, y1):
|
|
119
|
+
vals.extend(pixels[y][x0:x1])
|
|
120
|
+
vals.sort()
|
|
121
|
+
block_bgs.append(_percentile(vals, 0.85))
|
|
122
|
+
|
|
123
|
+
if len(block_bgs) < 2:
|
|
124
|
+
return 0.0
|
|
125
|
+
return max(block_bgs) - min(block_bgs)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def estimate_skew_angle(
|
|
129
|
+
image: GrayImage | Any,
|
|
130
|
+
max_angle_deg: float = 10.0,
|
|
131
|
+
step_deg: float = 0.5,
|
|
132
|
+
) -> float:
|
|
133
|
+
"""Estimate document micro-skew angle in degrees via projection-profile variance.
|
|
134
|
+
|
|
135
|
+
Positive angle means horizontal text lines slope downward to the right
|
|
136
|
+
(clockwise tilt in top-left image coordinates). Deskewing rotates by
|
|
137
|
+
``-skew_angle_deg``.
|
|
138
|
+
"""
|
|
139
|
+
gray = GrayImage.from_any(image)
|
|
140
|
+
w, h = gray.width, gray.height
|
|
141
|
+
if w < 8 or h < 8:
|
|
142
|
+
return 0.0
|
|
143
|
+
|
|
144
|
+
mean, std, _, _, _, _ = _image_stats(gray)
|
|
145
|
+
if std < 1.0:
|
|
146
|
+
return 0.0
|
|
147
|
+
|
|
148
|
+
# Uniform downsampling for speed on large images while preserving aspect ratio.
|
|
149
|
+
stride = max(1, max(w, h) // 160)
|
|
150
|
+
cx = (w - 1) / 2.0
|
|
151
|
+
cy = (h - 1) / 2.0
|
|
152
|
+
|
|
153
|
+
thresh = mean - 0.35 * std
|
|
154
|
+
fg_points: list[tuple[float, float, float]] = []
|
|
155
|
+
pixels = gray.pixels
|
|
156
|
+
for y in range(0, h, stride):
|
|
157
|
+
row = pixels[y]
|
|
158
|
+
dy = (y - cy) / stride
|
|
159
|
+
for x in range(0, w, stride):
|
|
160
|
+
p = row[x]
|
|
161
|
+
if p < thresh:
|
|
162
|
+
fg_points.append(((x - cx) / stride, dy, thresh - p))
|
|
163
|
+
|
|
164
|
+
if len(fg_points) < 10:
|
|
165
|
+
fg_points = []
|
|
166
|
+
for y in range(0, h, stride):
|
|
167
|
+
row = pixels[y]
|
|
168
|
+
dy = (y - cy) / stride
|
|
169
|
+
for x in range(0, w, stride):
|
|
170
|
+
p = row[x]
|
|
171
|
+
if p < mean:
|
|
172
|
+
fg_points.append(((x - cx) / stride, dy, mean - p))
|
|
173
|
+
|
|
174
|
+
if len(fg_points) < 10:
|
|
175
|
+
return 0.0
|
|
176
|
+
|
|
177
|
+
scaled_w = w / stride
|
|
178
|
+
scaled_h = h / stride
|
|
179
|
+
half_diag = int(math.ceil(math.hypot(scaled_w, scaled_h) / 2.0)) + 2
|
|
180
|
+
num_bins = 2 * half_diag + 4
|
|
181
|
+
|
|
182
|
+
def _projection_energy(angle_deg: float) -> float:
|
|
183
|
+
rad = math.radians(angle_deg)
|
|
184
|
+
sin_a = math.sin(rad)
|
|
185
|
+
cos_a = math.cos(rad)
|
|
186
|
+
bins = [0.0] * num_bins
|
|
187
|
+
offset = float(half_diag + 1)
|
|
188
|
+
for dx, dy, weight in fg_points:
|
|
189
|
+
# Project onto rotated y-axis for deskew angle (-angle_deg).
|
|
190
|
+
y_rot = -dx * sin_a + dy * cos_a + offset
|
|
191
|
+
idx = int(math.floor(y_rot))
|
|
192
|
+
if 0 <= idx < num_bins - 1:
|
|
193
|
+
frac = y_rot - idx
|
|
194
|
+
bins[idx] += weight * (1.0 - frac)
|
|
195
|
+
bins[idx + 1] += weight * frac
|
|
196
|
+
return sum(b * b for b in bins)
|
|
197
|
+
|
|
198
|
+
# Coarse search
|
|
199
|
+
step = max(0.1, float(step_deg))
|
|
200
|
+
num_steps = int(round((2.0 * max_angle_deg) / step))
|
|
201
|
+
best_angle = 0.0
|
|
202
|
+
best_energy = _projection_energy(0.0)
|
|
203
|
+
zero_energy = best_energy
|
|
204
|
+
|
|
205
|
+
for i in range(num_steps + 1):
|
|
206
|
+
angle = -max_angle_deg + i * step
|
|
207
|
+
energy = _projection_energy(angle)
|
|
208
|
+
if energy > best_energy:
|
|
209
|
+
best_energy = energy
|
|
210
|
+
best_angle = angle
|
|
211
|
+
|
|
212
|
+
# Fine refinement around best coarse angle
|
|
213
|
+
fine_step = min(0.1, step / 4.0)
|
|
214
|
+
fine_start = max(-max_angle_deg, best_angle - step)
|
|
215
|
+
fine_end = min(max_angle_deg, best_angle + step)
|
|
216
|
+
fine_steps = int(round((fine_end - fine_start) / fine_step))
|
|
217
|
+
for i in range(fine_steps + 1):
|
|
218
|
+
angle = fine_start + i * fine_step
|
|
219
|
+
energy = _projection_energy(angle)
|
|
220
|
+
if energy > best_energy:
|
|
221
|
+
best_energy = energy
|
|
222
|
+
best_angle = angle
|
|
223
|
+
|
|
224
|
+
# Prefer exact 0.0 if improvement over 0 deg is negligible.
|
|
225
|
+
if best_energy <= zero_energy * 1.001:
|
|
226
|
+
return 0.0
|
|
227
|
+
|
|
228
|
+
return round(best_angle, 3)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def estimate_char_height_px(image: GrayImage | Any) -> float:
|
|
232
|
+
"""Estimate typical character/line stroke height in pixels from horizontal runs."""
|
|
233
|
+
gray = GrayImage.from_any(image)
|
|
234
|
+
w, h = gray.width, gray.height
|
|
235
|
+
if w < 4 or h < 4:
|
|
236
|
+
return 0.0
|
|
237
|
+
|
|
238
|
+
flat: list[float] = []
|
|
239
|
+
for row in gray.pixels:
|
|
240
|
+
flat.extend(row)
|
|
241
|
+
n = len(flat)
|
|
242
|
+
mean = sum(flat) / n
|
|
243
|
+
std = math.sqrt(sum((v - mean) * (v - mean) for v in flat) / n)
|
|
244
|
+
if std < 2.0:
|
|
245
|
+
return 0.0
|
|
246
|
+
|
|
247
|
+
flat.sort()
|
|
248
|
+
bg_est = _percentile(flat, 0.85)
|
|
249
|
+
ink_thresh = bg_est - max(15.0, 0.5 * std)
|
|
250
|
+
min_ink_per_row = max(2, int(0.02 * w))
|
|
251
|
+
|
|
252
|
+
runs: list[int] = []
|
|
253
|
+
current_run = 0
|
|
254
|
+
for row in gray.pixels:
|
|
255
|
+
ink_count = sum(1 for v in row if v < ink_thresh)
|
|
256
|
+
if ink_count >= min_ink_per_row:
|
|
257
|
+
current_run += 1
|
|
258
|
+
elif current_run > 0:
|
|
259
|
+
runs.append(current_run)
|
|
260
|
+
current_run = 0
|
|
261
|
+
if current_run > 0:
|
|
262
|
+
runs.append(current_run)
|
|
263
|
+
|
|
264
|
+
if not runs:
|
|
265
|
+
return 0.0
|
|
266
|
+
|
|
267
|
+
runs.sort()
|
|
268
|
+
mid = len(runs) // 2
|
|
269
|
+
if len(runs) % 2 == 1:
|
|
270
|
+
return float(runs[mid])
|
|
271
|
+
return 0.5 * (runs[mid - 1] + runs[mid])
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def diagnose(
|
|
275
|
+
image: GrayImage | Any,
|
|
276
|
+
config: PreprocessConfig | None = None,
|
|
277
|
+
) -> QualityReport:
|
|
278
|
+
"""Run all lightweight quality diagnostics on a document image.
|
|
279
|
+
|
|
280
|
+
Unreadable flags are strictly advisory and never reject an image.
|
|
281
|
+
"""
|
|
282
|
+
gray = GrayImage.from_any(image)
|
|
283
|
+
cfg = config if config is not None else PreprocessConfig()
|
|
284
|
+
|
|
285
|
+
mean, std, min_val, max_val, p5, p95 = _image_stats(gray)
|
|
286
|
+
blur_score = compute_blur_score(gray)
|
|
287
|
+
contrast_score = std
|
|
288
|
+
illumination_unevenness = compute_illumination_unevenness(gray)
|
|
289
|
+
skew_angle_deg = estimate_skew_angle(
|
|
290
|
+
gray,
|
|
291
|
+
max_angle_deg=cfg.max_skew_search_deg,
|
|
292
|
+
step_deg=cfg.skew_step_deg,
|
|
293
|
+
)
|
|
294
|
+
estimated_char_height_px = estimate_char_height_px(gray)
|
|
295
|
+
aspect_ratio = gray.height / float(gray.width)
|
|
296
|
+
|
|
297
|
+
reasons: list[str] = []
|
|
298
|
+
if mean < 15.0 and p95 < 30.0:
|
|
299
|
+
reasons.append("crushed_blacks")
|
|
300
|
+
if mean > 245.0 and p5 > 235.0:
|
|
301
|
+
reasons.append("blown_highlights")
|
|
302
|
+
if contrast_score < 2.0 or (max_val - min_val) < cfg.min_dynamic_range:
|
|
303
|
+
reasons.append("flat_image")
|
|
304
|
+
if blur_score < cfg.blur_unreadable_threshold:
|
|
305
|
+
reasons.append("extreme_blur")
|
|
306
|
+
|
|
307
|
+
return QualityReport(
|
|
308
|
+
width=gray.width,
|
|
309
|
+
height=gray.height,
|
|
310
|
+
skew_angle_deg=skew_angle_deg,
|
|
311
|
+
blur_score=blur_score,
|
|
312
|
+
contrast_score=contrast_score,
|
|
313
|
+
illumination_unevenness=illumination_unevenness,
|
|
314
|
+
estimated_char_height_px=estimated_char_height_px,
|
|
315
|
+
aspect_ratio=aspect_ratio,
|
|
316
|
+
unreadable_flag=bool(reasons),
|
|
317
|
+
unreadable_reasons=tuple(reasons),
|
|
318
|
+
)
|
doc_preproc/geometry.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Exact 2D affine coordinate transformations for document preprocessing."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
import math
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class AffineTransform2D:
|
|
11
|
+
"""Immutable 2x3 affine transformation matrix.
|
|
12
|
+
|
|
13
|
+
Maps a point ``(x, y)`` to ``(x', y')`` via::
|
|
14
|
+
|
|
15
|
+
x' = a * x + b * y + tx
|
|
16
|
+
y' = c * x + d * y + ty
|
|
17
|
+
|
|
18
|
+
Image coordinates follow the standard top-left origin convention:
|
|
19
|
+
``x`` increases to the right and ``y`` increases downward.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
a: float = 1.0
|
|
23
|
+
b: float = 0.0
|
|
24
|
+
tx: float = 0.0
|
|
25
|
+
c: float = 0.0
|
|
26
|
+
d: float = 1.0
|
|
27
|
+
ty: float = 0.0
|
|
28
|
+
|
|
29
|
+
@classmethod
|
|
30
|
+
def identity(cls) -> AffineTransform2D:
|
|
31
|
+
"""Return the identity transform."""
|
|
32
|
+
return cls(1.0, 0.0, 0.0, 0.0, 1.0, 0.0)
|
|
33
|
+
|
|
34
|
+
@classmethod
|
|
35
|
+
def translation(cls, dx: float, dy: float) -> AffineTransform2D:
|
|
36
|
+
"""Return a pure translation by ``(dx, dy)``."""
|
|
37
|
+
return cls(1.0, 0.0, float(dx), 0.0, 1.0, float(dy))
|
|
38
|
+
|
|
39
|
+
@classmethod
|
|
40
|
+
def scale(cls, sx: float, sy: float | None = None) -> AffineTransform2D:
|
|
41
|
+
"""Return a scaling transform about the origin."""
|
|
42
|
+
sy_val = float(sx if sy is None else sy)
|
|
43
|
+
return cls(float(sx), 0.0, 0.0, 0.0, sy_val, 0.0)
|
|
44
|
+
|
|
45
|
+
@classmethod
|
|
46
|
+
def rotation(
|
|
47
|
+
cls,
|
|
48
|
+
angle_deg: float,
|
|
49
|
+
cx: float = 0.0,
|
|
50
|
+
cy: float = 0.0,
|
|
51
|
+
) -> AffineTransform2D:
|
|
52
|
+
"""Return a rotation by ``angle_deg`` around ``(cx, cy)``.
|
|
53
|
+
|
|
54
|
+
In image coordinates (``x`` right, ``y`` down), a positive angle
|
|
55
|
+
rotates clockwise: ``(1, 0) -> (cos(a), sin(a))``.
|
|
56
|
+
"""
|
|
57
|
+
rad = math.radians(angle_deg)
|
|
58
|
+
cos_a = math.cos(rad)
|
|
59
|
+
sin_a = math.sin(rad)
|
|
60
|
+
tx = cx - (cos_a * cx - sin_a * cy)
|
|
61
|
+
ty = cy - (sin_a * cx + cos_a * cy)
|
|
62
|
+
return cls(cos_a, -sin_a, tx, sin_a, cos_a, ty)
|
|
63
|
+
|
|
64
|
+
def determinant(self) -> float:
|
|
65
|
+
"""Return the determinant of the 2x2 linear component."""
|
|
66
|
+
return self.a * self.d - self.b * self.c
|
|
67
|
+
|
|
68
|
+
def forward(self, x: float, y: float) -> tuple[float, float]:
|
|
69
|
+
"""Map a point ``(x, y)`` from source coordinates to target coordinates."""
|
|
70
|
+
return (
|
|
71
|
+
self.a * x + self.b * y + self.tx,
|
|
72
|
+
self.c * x + self.d * y + self.ty,
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
def invert(self) -> AffineTransform2D:
|
|
76
|
+
"""Return the exact inverse ``AffineTransform2D``."""
|
|
77
|
+
det = self.determinant()
|
|
78
|
+
if abs(det) < 1e-12:
|
|
79
|
+
raise ValueError("Affine transform is singular and cannot be inverted.")
|
|
80
|
+
inv_a = self.d / det
|
|
81
|
+
inv_b = -self.b / det
|
|
82
|
+
inv_c = -self.c / det
|
|
83
|
+
inv_d = self.a / det
|
|
84
|
+
inv_tx = -(inv_a * self.tx + inv_b * self.ty)
|
|
85
|
+
inv_ty = -(inv_c * self.tx + inv_d * self.ty)
|
|
86
|
+
return AffineTransform2D(inv_a, inv_b, inv_tx, inv_c, inv_d, inv_ty)
|
|
87
|
+
|
|
88
|
+
def inverse(self, x_prime: float, y_prime: float) -> tuple[float, float]:
|
|
89
|
+
"""Map a point ``(x', y')`` from target coordinates back to source coordinates."""
|
|
90
|
+
det = self.determinant()
|
|
91
|
+
if abs(det) < 1e-12:
|
|
92
|
+
raise ValueError("Affine transform is singular and cannot be inverted.")
|
|
93
|
+
dx = x_prime - self.tx
|
|
94
|
+
dy = y_prime - self.ty
|
|
95
|
+
return (
|
|
96
|
+
(self.d * dx - self.b * dy) / det,
|
|
97
|
+
(-self.c * dx + self.a * dy) / det,
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
def compose(self, other: AffineTransform2D) -> AffineTransform2D:
|
|
101
|
+
"""Compose ``self`` followed by ``other``.
|
|
102
|
+
|
|
103
|
+
The resulting transform satisfies::
|
|
104
|
+
|
|
105
|
+
composed.forward(x, y) == other.forward(*self.forward(x, y))
|
|
106
|
+
"""
|
|
107
|
+
return AffineTransform2D(
|
|
108
|
+
a=other.a * self.a + other.b * self.c,
|
|
109
|
+
b=other.a * self.b + other.b * self.d,
|
|
110
|
+
tx=other.a * self.tx + other.b * self.ty + other.tx,
|
|
111
|
+
c=other.c * self.a + other.d * self.c,
|
|
112
|
+
d=other.c * self.b + other.d * self.d,
|
|
113
|
+
ty=other.c * self.tx + other.d * self.ty + other.ty,
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
def is_identity(self, tol: float = 1e-12) -> bool:
|
|
117
|
+
"""Return True if the matrix matches the identity within ``tol``."""
|
|
118
|
+
return (
|
|
119
|
+
abs(self.a - 1.0) <= tol
|
|
120
|
+
and abs(self.b) <= tol
|
|
121
|
+
and abs(self.tx) <= tol
|
|
122
|
+
and abs(self.c) <= tol
|
|
123
|
+
and abs(self.d - 1.0) <= tol
|
|
124
|
+
and abs(self.ty) <= tol
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
def as_matrix(
|
|
128
|
+
self,
|
|
129
|
+
) -> tuple[tuple[float, float, float], tuple[float, float, float]]:
|
|
130
|
+
"""Return the 2x3 matrix as nested tuples."""
|
|
131
|
+
return (
|
|
132
|
+
(self.a, self.b, self.tx),
|
|
133
|
+
(self.c, self.d, self.ty),
|
|
134
|
+
)
|
doc_preproc/models.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""Core data models for lightweight document image representation and results."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
import math
|
|
7
|
+
from typing import Any, Literal, Sequence
|
|
8
|
+
|
|
9
|
+
from .geometry import AffineTransform2D
|
|
10
|
+
|
|
11
|
+
ProfileName = Literal["receipt", "invoice", "crop"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _clamp_pixel(value: float) -> float:
|
|
15
|
+
if value < 0.0:
|
|
16
|
+
return 0.0
|
|
17
|
+
if value > 255.0:
|
|
18
|
+
return 255.0
|
|
19
|
+
return float(value)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _rgb_to_luma(pixel: Sequence[float | int]) -> float:
|
|
23
|
+
if len(pixel) == 1:
|
|
24
|
+
return _clamp_pixel(float(pixel[0]))
|
|
25
|
+
if len(pixel) >= 3:
|
|
26
|
+
r = float(pixel[0])
|
|
27
|
+
g = float(pixel[1])
|
|
28
|
+
b = float(pixel[2])
|
|
29
|
+
return _clamp_pixel(0.299 * r + 0.587 * g + 0.114 * b)
|
|
30
|
+
raise ValueError(f"Unsupported channel count: {len(pixel)}")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class GrayImage:
|
|
34
|
+
"""Lightweight pure-Python 2D grayscale image container.
|
|
35
|
+
|
|
36
|
+
Pixel intensities are stored in row-major order ``pixels[y][x]`` as floats
|
|
37
|
+
in ``[0.0, 255.0]``.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
__slots__ = ("width", "height", "pixels")
|
|
41
|
+
|
|
42
|
+
def __init__(self, pixels: Sequence[Sequence[float | int]]) -> None:
|
|
43
|
+
if not pixels:
|
|
44
|
+
raise ValueError("Image must have at least one row.")
|
|
45
|
+
first_row_len = len(pixels[0])
|
|
46
|
+
if first_row_len == 0:
|
|
47
|
+
raise ValueError("Image rows must have at least one column.")
|
|
48
|
+
|
|
49
|
+
normalized: list[list[float]] = []
|
|
50
|
+
for row in pixels:
|
|
51
|
+
if len(row) != first_row_len:
|
|
52
|
+
raise ValueError("All image rows must have equal length.")
|
|
53
|
+
normalized.append([_clamp_pixel(float(v)) for v in row])
|
|
54
|
+
|
|
55
|
+
self.height: int = len(normalized)
|
|
56
|
+
self.width: int = first_row_len
|
|
57
|
+
self.pixels: list[list[float]] = normalized
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def from_nested(cls, rows: Sequence[Sequence[Any]]) -> GrayImage:
|
|
61
|
+
"""Create a ``GrayImage`` from a 2D grayscale or 3D RGB nested sequence."""
|
|
62
|
+
if not rows:
|
|
63
|
+
raise ValueError("Image must have at least one row.")
|
|
64
|
+
first_row = rows[0]
|
|
65
|
+
if not first_row:
|
|
66
|
+
raise ValueError("Image rows must have at least one column.")
|
|
67
|
+
|
|
68
|
+
first_cell = first_row[0]
|
|
69
|
+
if isinstance(first_cell, (list, tuple)):
|
|
70
|
+
gray_rows = [
|
|
71
|
+
[_rgb_to_luma(cell) for cell in row]
|
|
72
|
+
for row in rows
|
|
73
|
+
]
|
|
74
|
+
return cls(gray_rows)
|
|
75
|
+
return cls(rows)
|
|
76
|
+
|
|
77
|
+
@classmethod
|
|
78
|
+
def from_any(cls, image: GrayImage | Any) -> GrayImage:
|
|
79
|
+
"""Accept a ``GrayImage``, 2D/3D numpy-like array, or nested sequence."""
|
|
80
|
+
if isinstance(image, cls):
|
|
81
|
+
return image
|
|
82
|
+
|
|
83
|
+
# Duck-typed support for numpy arrays without importing numpy.
|
|
84
|
+
if hasattr(image, "tolist") and hasattr(image, "shape"):
|
|
85
|
+
shape = getattr(image, "shape")
|
|
86
|
+
if len(shape) not in (2, 3):
|
|
87
|
+
raise ValueError(
|
|
88
|
+
f"Expected a 2D grayscale or 3D RGB array, got shape {shape!r}."
|
|
89
|
+
)
|
|
90
|
+
nested = image.tolist()
|
|
91
|
+
return cls.from_nested(nested)
|
|
92
|
+
|
|
93
|
+
if isinstance(image, Sequence):
|
|
94
|
+
return cls.from_nested(image)
|
|
95
|
+
|
|
96
|
+
raise TypeError(
|
|
97
|
+
f"Unsupported image type: {type(image).__name__}. "
|
|
98
|
+
"Expected GrayImage, 2D/3D numpy array, or nested sequence."
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
@classmethod
|
|
102
|
+
def filled(cls, width: int, height: int, value: float = 255.0) -> GrayImage:
|
|
103
|
+
"""Create a constant-intensity image of size ``(width, height)``."""
|
|
104
|
+
if width <= 0 or height <= 0:
|
|
105
|
+
raise ValueError("Image width and height must be positive.")
|
|
106
|
+
v = _clamp_pixel(value)
|
|
107
|
+
return cls([[v] * width for _ in range(height)])
|
|
108
|
+
|
|
109
|
+
def to_nested(self) -> list[list[float]]:
|
|
110
|
+
"""Return a deep copy of pixel data as nested Python lists."""
|
|
111
|
+
return [row[:] for row in self.pixels]
|
|
112
|
+
|
|
113
|
+
def copy(self) -> GrayImage:
|
|
114
|
+
"""Return an independent deep copy of this image."""
|
|
115
|
+
return GrayImage(self.to_nested())
|
|
116
|
+
|
|
117
|
+
def at(self, x: int, y: int) -> float:
|
|
118
|
+
"""Return the pixel value at integer coordinates ``(x, y)``."""
|
|
119
|
+
return self.pixels[y][x]
|
|
120
|
+
|
|
121
|
+
def sample_bilinear(self, x: float, y: float, fill: float = 255.0) -> float:
|
|
122
|
+
"""Sample the image at floating-point coordinates ``(x, y)`` using bilinear interpolation."""
|
|
123
|
+
if x < 0.0 or y < 0.0 or x > self.width - 1 or y > self.height - 1:
|
|
124
|
+
return fill
|
|
125
|
+
|
|
126
|
+
x0 = int(math.floor(x))
|
|
127
|
+
y0 = int(math.floor(y))
|
|
128
|
+
x1 = min(x0 + 1, self.width - 1)
|
|
129
|
+
y1 = min(y0 + 1, self.height - 1)
|
|
130
|
+
|
|
131
|
+
fx = x - x0
|
|
132
|
+
fy = y - y0
|
|
133
|
+
|
|
134
|
+
row0 = self.pixels[y0]
|
|
135
|
+
row1 = self.pixels[y1]
|
|
136
|
+
|
|
137
|
+
top = row0[x0] * (1.0 - fx) + row0[x1] * fx
|
|
138
|
+
bottom = row1[x0] * (1.0 - fx) + row1[x1] * fx
|
|
139
|
+
return top * (1.0 - fy) + bottom * fy
|
|
140
|
+
|
|
141
|
+
def __eq__(self, other: object) -> bool:
|
|
142
|
+
if not isinstance(other, GrayImage):
|
|
143
|
+
return NotImplemented
|
|
144
|
+
return (
|
|
145
|
+
self.width == other.width
|
|
146
|
+
and self.height == other.height
|
|
147
|
+
and self.pixels == other.pixels
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
def __repr__(self) -> str:
|
|
151
|
+
return f"GrayImage(width={self.width}, height={self.height})"
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@dataclass(frozen=True)
|
|
155
|
+
class QualityReport:
|
|
156
|
+
"""Diagnostic quality metrics for a document image."""
|
|
157
|
+
|
|
158
|
+
width: int
|
|
159
|
+
height: int
|
|
160
|
+
skew_angle_deg: float
|
|
161
|
+
blur_score: float
|
|
162
|
+
contrast_score: float
|
|
163
|
+
illumination_unevenness: float
|
|
164
|
+
estimated_char_height_px: float
|
|
165
|
+
aspect_ratio: float
|
|
166
|
+
unreadable_flag: bool
|
|
167
|
+
unreadable_reasons: tuple[str, ...]
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
@dataclass(frozen=True)
|
|
171
|
+
class PreprocessConfig:
|
|
172
|
+
"""Thresholds and parameters controlling quality diagnosis and preprocessing."""
|
|
173
|
+
|
|
174
|
+
skew_threshold_deg: float = 1.0
|
|
175
|
+
max_skew_search_deg: float = 10.0
|
|
176
|
+
skew_step_deg: float = 0.5
|
|
177
|
+
contrast_threshold: float = 28.0
|
|
178
|
+
illumination_threshold: float = 35.0
|
|
179
|
+
blur_unreadable_threshold: float = 5.0
|
|
180
|
+
min_dynamic_range: float = 12.0
|
|
181
|
+
fill_value: float = 255.0
|
|
182
|
+
|
|
183
|
+
@classmethod
|
|
184
|
+
def for_profile(cls, profile: str) -> PreprocessConfig:
|
|
185
|
+
"""Return tuned default configuration for a named document profile."""
|
|
186
|
+
if profile == "receipt":
|
|
187
|
+
return cls(
|
|
188
|
+
skew_threshold_deg=1.0,
|
|
189
|
+
max_skew_search_deg=10.0,
|
|
190
|
+
skew_step_deg=0.5,
|
|
191
|
+
contrast_threshold=28.0,
|
|
192
|
+
illumination_threshold=30.0,
|
|
193
|
+
)
|
|
194
|
+
if profile == "invoice":
|
|
195
|
+
return cls(
|
|
196
|
+
skew_threshold_deg=0.8,
|
|
197
|
+
max_skew_search_deg=10.0,
|
|
198
|
+
skew_step_deg=0.5,
|
|
199
|
+
contrast_threshold=26.0,
|
|
200
|
+
illumination_threshold=35.0,
|
|
201
|
+
)
|
|
202
|
+
if profile == "crop":
|
|
203
|
+
return cls(
|
|
204
|
+
skew_threshold_deg=0.75,
|
|
205
|
+
max_skew_search_deg=10.0,
|
|
206
|
+
skew_step_deg=0.5,
|
|
207
|
+
contrast_threshold=25.0,
|
|
208
|
+
illumination_threshold=32.0,
|
|
209
|
+
)
|
|
210
|
+
raise ValueError(
|
|
211
|
+
f"Unknown profile {profile!r}. Expected 'receipt', 'invoice', or 'crop'."
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
@dataclass(frozen=True)
|
|
216
|
+
class CropPlan:
|
|
217
|
+
"""Computed local re-read crop geometry and exact coordinate transform."""
|
|
218
|
+
|
|
219
|
+
bbox: tuple[float, float, float, float]
|
|
220
|
+
scale_factor: float
|
|
221
|
+
output_size: tuple[int, int]
|
|
222
|
+
transform: AffineTransform2D
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
@dataclass(frozen=True)
|
|
226
|
+
class PreprocessResult:
|
|
227
|
+
"""Output of adaptive document preprocessing."""
|
|
228
|
+
|
|
229
|
+
image: GrayImage
|
|
230
|
+
report: QualityReport
|
|
231
|
+
transform: AffineTransform2D
|
|
232
|
+
applied_transforms: tuple[str, ...]
|
|
233
|
+
is_noop: bool
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
"""Adaptive, non-destructive document preprocessing and local crop planning."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from .diagnose import _percentile, compute_contrast_score, diagnose
|
|
9
|
+
from .geometry import AffineTransform2D
|
|
10
|
+
from .models import (
|
|
11
|
+
CropPlan,
|
|
12
|
+
GrayImage,
|
|
13
|
+
PreprocessConfig,
|
|
14
|
+
PreprocessResult,
|
|
15
|
+
ProfileName,
|
|
16
|
+
_clamp_pixel,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def deskew_image(
|
|
21
|
+
image: GrayImage,
|
|
22
|
+
angle_deg: float,
|
|
23
|
+
fill_value: float = 255.0,
|
|
24
|
+
) -> tuple[GrayImage, AffineTransform2D]:
|
|
25
|
+
"""Deskew an image by rotating ``-angle_deg`` around its center using bilinear interpolation.
|
|
26
|
+
|
|
27
|
+
Returns ``(deskewed_image, transform)`` where ``transform`` maps original
|
|
28
|
+
image coordinates ``(x, y)`` to deskewed coordinates ``(x', y')``, and
|
|
29
|
+
``transform.inverse(x', y')`` maps back to original coordinates.
|
|
30
|
+
"""
|
|
31
|
+
w, h = image.width, image.height
|
|
32
|
+
cx = (w - 1) / 2.0
|
|
33
|
+
cy = (h - 1) / 2.0
|
|
34
|
+
|
|
35
|
+
transform = AffineTransform2D.rotation(-angle_deg, cx, cy)
|
|
36
|
+
inv = transform.invert()
|
|
37
|
+
|
|
38
|
+
out_rows: list[list[float]] = []
|
|
39
|
+
for y_out in range(h):
|
|
40
|
+
row: list[float] = []
|
|
41
|
+
base_x = inv.b * y_out + inv.tx
|
|
42
|
+
base_y = inv.d * y_out + inv.ty
|
|
43
|
+
for x_out in range(w):
|
|
44
|
+
src_x = inv.a * x_out + base_x
|
|
45
|
+
src_y = inv.c * x_out + base_y
|
|
46
|
+
row.append(image.sample_bilinear(src_x, src_y, fill=fill_value))
|
|
47
|
+
out_rows.append(row)
|
|
48
|
+
|
|
49
|
+
return GrayImage(out_rows), transform
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def normalize_illumination(
|
|
53
|
+
image: GrayImage,
|
|
54
|
+
grid_rows: int = 6,
|
|
55
|
+
grid_cols: int = 6,
|
|
56
|
+
target_background: float = 245.0,
|
|
57
|
+
) -> GrayImage:
|
|
58
|
+
"""Remove uneven lighting/shadows via smooth local background division.
|
|
59
|
+
|
|
60
|
+
Non-destructive: preserves continuous grayscale tone without binarization.
|
|
61
|
+
"""
|
|
62
|
+
w, h = image.width, image.height
|
|
63
|
+
rows = max(2, min(grid_rows, max(2, h // 8)))
|
|
64
|
+
cols = max(2, min(grid_cols, max(2, w // 8)))
|
|
65
|
+
if w < 4 or h < 4:
|
|
66
|
+
return image.copy()
|
|
67
|
+
|
|
68
|
+
pixels = image.pixels
|
|
69
|
+
bg_grid: list[list[float]] = []
|
|
70
|
+
row_centers: list[float] = []
|
|
71
|
+
col_centers: list[float] = []
|
|
72
|
+
|
|
73
|
+
for r in range(rows):
|
|
74
|
+
y0 = (r * h) // rows
|
|
75
|
+
y1 = ((r + 1) * h) // rows
|
|
76
|
+
row_centers.append(0.5 * (y0 + y1 - 1))
|
|
77
|
+
grid_row: list[float] = []
|
|
78
|
+
for c in range(cols):
|
|
79
|
+
x0 = (c * w) // cols
|
|
80
|
+
x1 = ((c + 1) * w) // cols
|
|
81
|
+
if r == 0:
|
|
82
|
+
col_centers.append(0.5 * (x0 + x1 - 1))
|
|
83
|
+
vals: list[float] = []
|
|
84
|
+
for y in range(y0, max(y0 + 1, y1)):
|
|
85
|
+
vals.extend(pixels[y][x0 : max(x0 + 1, x1)])
|
|
86
|
+
vals.sort()
|
|
87
|
+
grid_row.append(max(1.0, _percentile(vals, 0.85)))
|
|
88
|
+
bg_grid.append(grid_row)
|
|
89
|
+
|
|
90
|
+
def _interp_1d(coord: float, centers: list[float]) -> tuple[int, int, float]:
|
|
91
|
+
if coord <= centers[0]:
|
|
92
|
+
return 0, 0, 0.0
|
|
93
|
+
if coord >= centers[-1]:
|
|
94
|
+
last = len(centers) - 1
|
|
95
|
+
return last, last, 0.0
|
|
96
|
+
for idx in range(len(centers) - 1):
|
|
97
|
+
c0 = centers[idx]
|
|
98
|
+
c1 = centers[idx + 1]
|
|
99
|
+
if c0 <= coord <= c1:
|
|
100
|
+
span = c1 - c0
|
|
101
|
+
frac = (coord - c0) / span if span > 1e-9 else 0.0
|
|
102
|
+
return idx, idx + 1, frac
|
|
103
|
+
last = len(centers) - 1
|
|
104
|
+
return last, last, 0.0
|
|
105
|
+
|
|
106
|
+
x_interp = [_interp_1d(float(x), col_centers) for x in range(w)]
|
|
107
|
+
out_rows: list[list[float]] = []
|
|
108
|
+
|
|
109
|
+
for y in range(h):
|
|
110
|
+
r0, r1, fy = _interp_1d(float(y), row_centers)
|
|
111
|
+
bg_r0 = bg_grid[r0]
|
|
112
|
+
bg_r1 = bg_grid[r1]
|
|
113
|
+
src_row = pixels[y]
|
|
114
|
+
out_row: list[float] = []
|
|
115
|
+
for x in range(w):
|
|
116
|
+
c0, c1, fx = x_interp[x]
|
|
117
|
+
top = bg_r0[c0] * (1.0 - fx) + bg_r0[c1] * fx
|
|
118
|
+
bottom = bg_r1[c0] * (1.0 - fx) + bg_r1[c1] * fx
|
|
119
|
+
local_bg = max(1.0, top * (1.0 - fy) + bottom * fy)
|
|
120
|
+
out_row.append(_clamp_pixel(src_row[x] * (target_background / local_bg)))
|
|
121
|
+
out_rows.append(out_row)
|
|
122
|
+
|
|
123
|
+
return GrayImage(out_rows)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def stretch_contrast(
|
|
127
|
+
image: GrayImage,
|
|
128
|
+
low_quantile: float = 0.02,
|
|
129
|
+
high_quantile: float = 0.98,
|
|
130
|
+
out_low: float = 10.0,
|
|
131
|
+
out_high: float = 250.0,
|
|
132
|
+
) -> GrayImage:
|
|
133
|
+
"""Apply non-destructive linear percentile contrast stretching."""
|
|
134
|
+
flat: list[float] = []
|
|
135
|
+
for row in image.pixels:
|
|
136
|
+
flat.extend(row)
|
|
137
|
+
flat.sort()
|
|
138
|
+
|
|
139
|
+
p_low = _percentile(flat, low_quantile)
|
|
140
|
+
p_high = _percentile(flat, high_quantile)
|
|
141
|
+
span = p_high - p_low
|
|
142
|
+
if span < 1e-6:
|
|
143
|
+
return image.copy()
|
|
144
|
+
|
|
145
|
+
scale = (out_high - out_low) / span
|
|
146
|
+
out_rows = [
|
|
147
|
+
[_clamp_pixel((v - p_low) * scale + out_low) for v in row]
|
|
148
|
+
for row in image.pixels
|
|
149
|
+
]
|
|
150
|
+
return GrayImage(out_rows)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def preprocess(
|
|
154
|
+
image: GrayImage | Any,
|
|
155
|
+
profile: ProfileName | str = "receipt",
|
|
156
|
+
config: PreprocessConfig | None = None,
|
|
157
|
+
) -> PreprocessResult:
|
|
158
|
+
"""Run quality diagnosis and adaptive, non-destructive preprocessing.
|
|
159
|
+
|
|
160
|
+
- Never mutates the input image.
|
|
161
|
+
- Clean images take a zero-transform no-op fast path (``is_noop=True``).
|
|
162
|
+
- Never performs OCR, generative synthesis, or hard binarization.
|
|
163
|
+
"""
|
|
164
|
+
gray = GrayImage.from_any(image)
|
|
165
|
+
cfg = config if config is not None else PreprocessConfig.for_profile(profile)
|
|
166
|
+
report = diagnose(gray, config=cfg)
|
|
167
|
+
|
|
168
|
+
is_flat = "flat_image" in report.unreadable_reasons
|
|
169
|
+
need_deskew = (not is_flat) and (abs(report.skew_angle_deg) > cfg.skew_threshold_deg)
|
|
170
|
+
need_illum = (not is_flat) and (
|
|
171
|
+
report.illumination_unevenness > cfg.illumination_threshold
|
|
172
|
+
)
|
|
173
|
+
need_contrast = (not is_flat) and (report.contrast_score < cfg.contrast_threshold)
|
|
174
|
+
|
|
175
|
+
if not (need_deskew or need_illum or need_contrast):
|
|
176
|
+
return PreprocessResult(
|
|
177
|
+
image=gray.copy(),
|
|
178
|
+
report=report,
|
|
179
|
+
transform=AffineTransform2D.identity(),
|
|
180
|
+
applied_transforms=(),
|
|
181
|
+
is_noop=True,
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
current = gray.copy()
|
|
185
|
+
total_transform = AffineTransform2D.identity()
|
|
186
|
+
applied: list[str] = []
|
|
187
|
+
|
|
188
|
+
if need_deskew:
|
|
189
|
+
current, deskew_tf = deskew_image(
|
|
190
|
+
current,
|
|
191
|
+
report.skew_angle_deg,
|
|
192
|
+
fill_value=cfg.fill_value,
|
|
193
|
+
)
|
|
194
|
+
total_transform = total_transform.compose(deskew_tf)
|
|
195
|
+
applied.append("deskew")
|
|
196
|
+
|
|
197
|
+
if need_illum:
|
|
198
|
+
current = normalize_illumination(current)
|
|
199
|
+
applied.append("illumination_normalization")
|
|
200
|
+
if not need_contrast:
|
|
201
|
+
need_contrast = compute_contrast_score(current) < cfg.contrast_threshold
|
|
202
|
+
|
|
203
|
+
if need_contrast:
|
|
204
|
+
current = stretch_contrast(current)
|
|
205
|
+
applied.append("contrast_normalization")
|
|
206
|
+
|
|
207
|
+
return PreprocessResult(
|
|
208
|
+
image=current,
|
|
209
|
+
report=report,
|
|
210
|
+
transform=total_transform,
|
|
211
|
+
applied_transforms=tuple(applied),
|
|
212
|
+
is_noop=False,
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def compute_crop_plan(
|
|
217
|
+
bbox: tuple[float, float, float, float],
|
|
218
|
+
image_size: tuple[int, int],
|
|
219
|
+
estimated_char_height_px: float,
|
|
220
|
+
target_char_height_px: float = 28.0,
|
|
221
|
+
padding_ratio: float = 0.15,
|
|
222
|
+
min_scale: float = 0.5,
|
|
223
|
+
max_scale: float = 4.0,
|
|
224
|
+
) -> CropPlan:
|
|
225
|
+
"""Compute an optimal padded crop box, scale factor, and exact coordinate transform.
|
|
226
|
+
|
|
227
|
+
Args:
|
|
228
|
+
bbox: ``(x0, y0, x1, y1)`` region of interest in original image coordinates.
|
|
229
|
+
image_size: ``(width, height)`` of the source image.
|
|
230
|
+
estimated_char_height_px: Estimated character/line height in the source image.
|
|
231
|
+
target_char_height_px: Desired character height in the cropped output.
|
|
232
|
+
padding_ratio: Fractional padding added around ``bbox`` on each side.
|
|
233
|
+
min_scale: Lower bound for the computed scale factor.
|
|
234
|
+
max_scale: Upper bound for the computed scale factor.
|
|
235
|
+
|
|
236
|
+
Returns:
|
|
237
|
+
``CropPlan`` whose ``transform`` maps original image coordinates to
|
|
238
|
+
cropped-and-scaled output coordinates, and ``transform.inverse`` maps
|
|
239
|
+
output coordinates back to the original image.
|
|
240
|
+
"""
|
|
241
|
+
x0, y0, x1, y1 = (float(v) for v in bbox)
|
|
242
|
+
width, height = int(image_size[0]), int(image_size[1])
|
|
243
|
+
|
|
244
|
+
if width <= 0 or height <= 0:
|
|
245
|
+
raise ValueError("image_size dimensions must be positive.")
|
|
246
|
+
if x1 <= x0 or y1 <= y0:
|
|
247
|
+
raise ValueError("bbox must satisfy x1 > x0 and y1 > y0.")
|
|
248
|
+
if target_char_height_px <= 0.0:
|
|
249
|
+
raise ValueError("target_char_height_px must be positive.")
|
|
250
|
+
|
|
251
|
+
bw = x1 - x0
|
|
252
|
+
bh = y1 - y0
|
|
253
|
+
pad_x = max(2.0, bw * padding_ratio)
|
|
254
|
+
pad_y = max(2.0, bh * padding_ratio)
|
|
255
|
+
|
|
256
|
+
px0 = max(0.0, x0 - pad_x)
|
|
257
|
+
py0 = max(0.0, y0 - pad_y)
|
|
258
|
+
px1 = min(float(width), x1 + pad_x)
|
|
259
|
+
py1 = min(float(height), y1 + pad_y)
|
|
260
|
+
|
|
261
|
+
if px1 <= px0 or py1 <= py0:
|
|
262
|
+
raise ValueError("Clamped crop bounding box is empty.")
|
|
263
|
+
|
|
264
|
+
if estimated_char_height_px > 0.0:
|
|
265
|
+
raw_scale = target_char_height_px / estimated_char_height_px
|
|
266
|
+
else:
|
|
267
|
+
raw_scale = 1.0
|
|
268
|
+
scale = max(min_scale, min(max_scale, raw_scale))
|
|
269
|
+
|
|
270
|
+
out_w = max(1, int(math.ceil((px1 - px0) * scale)))
|
|
271
|
+
out_h = max(1, int(math.ceil((py1 - py0) * scale)))
|
|
272
|
+
|
|
273
|
+
transform = AffineTransform2D.translation(-px0, -py0).compose(
|
|
274
|
+
AffineTransform2D.scale(scale, scale)
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
return CropPlan(
|
|
278
|
+
bbox=(px0, py0, px1, py1),
|
|
279
|
+
scale_factor=scale,
|
|
280
|
+
output_size=(out_w, out_h),
|
|
281
|
+
transform=transform,
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def apply_crop_plan(
|
|
286
|
+
image: GrayImage | Any,
|
|
287
|
+
plan: CropPlan,
|
|
288
|
+
fill_value: float = 255.0,
|
|
289
|
+
) -> GrayImage:
|
|
290
|
+
"""Render a ``CropPlan`` using bilinear interpolation."""
|
|
291
|
+
gray = GrayImage.from_any(image)
|
|
292
|
+
out_w, out_h = plan.output_size
|
|
293
|
+
inv = plan.transform.invert()
|
|
294
|
+
|
|
295
|
+
out_rows: list[list[float]] = []
|
|
296
|
+
for y_out in range(out_h):
|
|
297
|
+
row: list[float] = []
|
|
298
|
+
base_x = inv.b * y_out + inv.tx
|
|
299
|
+
base_y = inv.d * y_out + inv.ty
|
|
300
|
+
for x_out in range(out_w):
|
|
301
|
+
src_x = inv.a * x_out + base_x
|
|
302
|
+
src_y = inv.c * x_out + base_y
|
|
303
|
+
row.append(gray.sample_bilinear(src_x, src_y, fill=fill_value))
|
|
304
|
+
out_rows.append(row)
|
|
305
|
+
|
|
306
|
+
return GrayImage(out_rows)
|
doc_preproc/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: doc-preproc
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Lightweight, non-destructive document image quality diagnosis, adaptive preprocessing, and exact 2D coordinate mapping.
|
|
5
|
+
Author: doc-preproc contributors
|
|
6
|
+
License: MIT
|
|
7
|
+
Keywords: document,preprocessing,deskew,image-quality,affine-transform
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Image Processing
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
Provides-Extra: dev
|
|
20
|
+
Requires-Dist: pytest >=7.0 ; extra == 'dev'
|
|
21
|
+
|
|
22
|
+
# doc-preproc
|
|
23
|
+
|
|
24
|
+
Lightweight, zero-dependency, non-destructive document image quality diagnosis, adaptive preprocessing, and exact 2D coordinate mapping for Python (`>=3.10`).
|
|
25
|
+
|
|
26
|
+
## Design Principles
|
|
27
|
+
|
|
28
|
+
- **Pure Python core, zero required runtime dependencies**: Operates on a lightweight `GrayImage` 2D grid (`0..255`) with seamless duck-typed support for 2D grayscale or 3D RGB `numpy` arrays when passed in.
|
|
29
|
+
- **Non-destructive by default**: Never mutates input images and never applies destructive hard binarization.
|
|
30
|
+
- **No-op fast path**: Clean images with negligible skew, healthy contrast, and even lighting incur zero pixel transforms (`is_noop=True`, identity `AffineTransform2D`).
|
|
31
|
+
- **Exact reversible geometry**: Every geometric transform returns an exact 2x3 `AffineTransform2D` with `forward(x, y)` and `inverse(x', y')` mapping between original and preprocessed coordinates.
|
|
32
|
+
- **Strict safety boundary**: Performs deterministic signal processing only—no OCR inference, no generative super-resolution/image synthesis, and no network calls.
|
|
33
|
+
|
|
34
|
+
## Installation
|
|
35
|
+
|
|
36
|
+
Install in editable mode from a local checkout:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install -e .
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Quick Start
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from doc_preproc import GrayImage, compute_crop_plan, diagnose, preprocess
|
|
46
|
+
|
|
47
|
+
# Construct from nested lists (or pass a 2D/3D numpy array directly)
|
|
48
|
+
image = GrayImage.filled(120, 80, value=250.0)
|
|
49
|
+
|
|
50
|
+
# 1. Inspect image quality
|
|
51
|
+
report = diagnose(image)
|
|
52
|
+
print(report.skew_angle_deg, report.blur_score, report.contrast_score)
|
|
53
|
+
|
|
54
|
+
# 2. Run adaptive, non-destructive preprocessing
|
|
55
|
+
result = preprocess(image, profile="receipt")
|
|
56
|
+
print(result.is_noop, result.applied_transforms)
|
|
57
|
+
|
|
58
|
+
# Map a point from preprocessed coordinates back to original image coordinates
|
|
59
|
+
orig_x, orig_y = result.transform.inverse(50.0, 30.0)
|
|
60
|
+
|
|
61
|
+
# 3. Compute an optimal local re-read crop plan with exact coordinate transform
|
|
62
|
+
plan = compute_crop_plan(
|
|
63
|
+
bbox=(10.0, 20.0, 90.0, 45.0),
|
|
64
|
+
image_size=(image.width, image.height),
|
|
65
|
+
estimated_char_height_px=14.0,
|
|
66
|
+
target_char_height_px=28.0,
|
|
67
|
+
)
|
|
68
|
+
print(plan.scale_factor, plan.output_size)
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Public API
|
|
72
|
+
|
|
73
|
+
- `GrayImage`: Row-major 2D grayscale container with `from_nested`, `from_any`, `to_nested`, `copy`, and bilinear sampling.
|
|
74
|
+
- `AffineTransform2D`: Composable 2x3 affine matrix (`identity`, `translation`, `scale`, `rotation`, `forward`, `inverse`, `invert`, `compose`).
|
|
75
|
+
- `diagnose(image, config=None) -> QualityReport`: Computes `skew_angle_deg`, `blur_score`, `contrast_score`, `illumination_unevenness`, `estimated_char_height_px`, `aspect_ratio`, and advisory `unreadable_flag` / `unreadable_reasons`.
|
|
76
|
+
- `preprocess(image, profile="receipt"|"invoice"|"crop", config=None) -> PreprocessResult`: Runs diagnosis and applies only needed transforms (`deskew`, `illumination_normalization`, `contrast_normalization`), returning `(image, report, transform, applied_transforms, is_noop)`.
|
|
77
|
+
- `compute_crop_plan(...) -> CropPlan` & `apply_crop_plan(image, plan) -> GrayImage`: Computes padded crop bounds, optimal scale factor, and exact coordinate transform for local re-read regions.
|
|
78
|
+
|
|
79
|
+
## Running Tests
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
PYTHONPATH=src python -m unittest discover -s tests -v
|
|
83
|
+
```
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
doc_preproc/__init__.py,sha256=HVrElJsIQAhVMX5ib_VYdm3LTw6Jipy3Zq17HPt577M,1084
|
|
2
|
+
doc_preproc/diagnose.py,sha256=jjc2WDNlWwPYgDHjhC19RKup3-hDiVDhR42bmak3oeY,9728
|
|
3
|
+
doc_preproc/geometry.py,sha256=zeQDYVE0fHJKWC59VIJpooR6NEQUgVOdsj-Qe4jkqls,4623
|
|
4
|
+
doc_preproc/models.py,sha256=nZ4mzeeNayoxI3PnSaFI0_gRTi5QWpwd4UI3h2MHNeg,7620
|
|
5
|
+
doc_preproc/preprocess.py,sha256=OF5Tk8gnInJz1e_QFrv2WwGq8UPNyLQNMOeriP3QBpo,10052
|
|
6
|
+
doc_preproc/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
doc_preproc-0.1.0.dist-info/METADATA,sha256=MRE1LIWk5PXE6b1WornAAxl7VefwNTbTzgirD5iT7L4,4096
|
|
8
|
+
doc_preproc-0.1.0.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92
|
|
9
|
+
doc_preproc-0.1.0.dist-info/top_level.txt,sha256=BwIfmodUS3b7BLX67n3zbrg2fq0B_1SPHms6rk0QR7U,12
|
|
10
|
+
doc_preproc-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
doc_preproc
|