Spaces:
Sleeping

File size: 17,740 Bytes
0776964
 
 
 
 
 
 
 
 
 
 
 
 
 
decd94d
 
 
 
 
 
 
 
 
 
 
 
0776964
 
 
decd94d
 
0776964
 
 
 
 
 
 
decd94d
0776964
 
decd94d
 
 
 
 
 
 
 
 
0776964
 
 
 
decd94d
 
 
 
0776964
decd94d
 
 
 
 
 
7a14a48
decd94d
 
 
 
 
 
 
 
 
 
 
 
 
 
0776964
decd94d
 
 
 
0776964
decd94d
 
0776964
 
 
decd94d
0776964
 
decd94d
 
0776964
decd94d
 
 
 
 
 
 
 
0776964
 
 
 
 
 
 
 
 
decd94d
0776964
decd94d
0776964
 
decd94d
0776964
decd94d
0776964
 
decd94d
 
0776964
 
decd94d
0776964
 
decd94d
 
 
0776964
 
decd94d
 
0776964
 
 
 
 
 
decd94d
 
0776964
 
decd94d
 
 
 
 
0776964
decd94d
 
 
 
 
 
 
 
0776964
 
 
 
 
decd94d
 
0776964
 
decd94d
 
 
0776964
 
decd94d
 
0776964
 
decd94d
 
0776964
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
decd94d
0776964
 
 
decd94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0776964
decd94d
0776964
decd94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0776964
decd94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0776964
decd94d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0776964
 
decd94d
 
 
0776964
 
 
 
 
 
 
 
 
 
 
 
decd94d
 
 
0776964
decd94d
 
 
 
 
 
0776964
 
 
 
 
 
decd94d
 
 
 
 
 
 
 
 
 
0776964
 
 
 
 
 
 
 
decd94d
0776964
 
decd94d
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
"""Tiền xử lý ảnh crop dòng cho OCR tài liệu in cũ.

Nguyên tắc: mô hình rec (PP-OCRv5) được huấn luyện trên ảnh tự nhiên,
nên KHÔNG nhị phân hóa cứng và KHÔNG làm mờ nét chữ. Mặc định chỉ:
  1. chuẩn hóa nền (flat-field bằng morphological closing) — khử ố vàng,
     chênh sáng;
  2. kéo giãn tương phản theo percentile — nền về trắng, chữ đậm trở lại
     (bù việc phép chia nền làm chữ bạc màu);
  3. upscale về target_height rồi sharpen nhẹ — bù mờ do nội suy.
Các bước còn lại (denoise, CLAHE, khử bleed-through, nhị phân hóa, deskew,
morph clean) là tùy chọn, mặc định tắt.

Test riêng ngoài pipeline: dùng test_preprocessor.py trong cùng thư mục.
"""

import cv2
import numpy as np
import argparse
import os
from pathlib import Path


class ImagePreprocessor:
    def __init__(self,
                 to_grayscale: bool = True,
                 normalize_bg: bool = True,
                 denoise: bool = False,
                 denoise_method: str = "bilateral",  # bilateral | nlm | gaussian
                 clahe: bool = False,
                 clahe_clip: float = 2.0,
                 clahe_grid: int = 8,
                 contrast_stretch: bool = True,
                 stretch_low_pct: float = 1.0,
                 stretch_high_pct: float = 90.0,
                 suppress_bleed: bool = False,
                 binarize: bool = False,
                 binarize_method: str = "sauvola",  # otsu | adaptive | sauvola
                 deskew: bool = False,
                 sharpen: bool = True,
                 sharpen_amount: float = 0.5,
                 morph_clean: bool = False,
                 target_height: int = 48,
                 padding: int = 4):
        self.to_grayscale = to_grayscale
        self.normalize_bg = normalize_bg
        self.denoise = denoise
        self.denoise_method = denoise_method
        self.clahe = clahe
        self.clahe_clip = clahe_clip
        self.clahe_grid = clahe_grid
        self.contrast_stretch = contrast_stretch
        self.stretch_low_pct = stretch_low_pct
        self.stretch_high_pct = stretch_high_pct
        self.suppress_bleed = suppress_bleed
        self.binarize = binarize
        self.binarize_method = binarize_method
        self.deskew = deskew
        self.sharpen = sharpen
        self.sharpen_amount = sharpen_amount
        self.morph_clean = morph_clean
        self.target_height = target_height
        self.padding = padding

    def process(self, image: np.ndarray,
                verbose: bool = False) -> np.ndarray:

        if image is None or image.size == 0:
            return image

        steps = {}
        img = image.copy()
        steps["original"] = img.copy()

        # 1. Grayscale
        if len(img.shape) == 3:
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        else:
            gray = img.copy()
        steps["grayscale"] = gray.copy()

        # 2. Chuẩn hóa nền (flat-field)
        if self.normalize_bg:
            gray = self._normalize_background(gray)
            steps["bg_norm"] = gray.copy()

        # 3. Khử nhiễu (tùy chọn) — bilateral giữ biên nét, không dùng blur
        if self.denoise:
            if self.denoise_method == "nlm":
                gray = cv2.fastNlMeansDenoising(
                    gray, h=7, templateWindowSize=7, searchWindowSize=21)
            elif self.denoise_method == "gaussian":
                gray = cv2.GaussianBlur(gray, (3, 3), 0)
            else:
                gray = cv2.bilateralFilter(gray, 5, 30, 30)
            steps["denoise"] = gray.copy()

        # 4. CLAHE (tùy chọn) — dễ gây nền loang lổ trên crop dòng
        if self.clahe:
            clahe_obj = cv2.createCLAHE(
                clipLimit=self.clahe_clip,
                tileGridSize=(self.clahe_grid, self.clahe_grid)
            )
            gray = clahe_obj.apply(gray)
            steps["clahe"] = gray.copy()

        # 5. Kéo giãn tương phản theo percentile
        if self.contrast_stretch:
            gray = self._contrast_stretch(gray)
            steps["stretch"] = gray.copy()

        # 6. Khử bleed-through mềm (tùy chọn)
        if self.suppress_bleed:
            gray = self._suppress_bleed(gray)
            steps["bleed"] = gray.copy()

        # 7. Nhị phân hóa (tùy chọn — chỉ nên dùng để debug/detection)
        if self.binarize:
            gray = self._binarize(gray)
            steps["binarize"] = gray.copy()

        # 8. Deskew (tùy chọn — chỉ hợp lý ở mức trang, không nên với crop dòng)
        if self.deskew:
            gray = self._deskew(gray)
            steps["deskew"] = gray.copy()

        if self.morph_clean:
            gray = self._morph_clean(gray)
            steps["morph_clean"] = gray.copy()

        # 9. Upscale về target_height
        ch, cw = gray.shape[:2]
        if ch < self.target_height:
            scale = self.target_height / ch
            new_w = max(1, int(cw * scale))
            gray = cv2.resize(
                gray, (new_w, self.target_height),
                interpolation=cv2.INTER_CUBIC
            )
            steps["upscale"] = gray.copy()

        # 10. Sharpen nhẹ SAU upscale để bù mờ do nội suy
        if self.sharpen:
            gray = self._sharpen(gray)
            steps["sharpen"] = gray.copy()

        if self.padding > 0:
            gray = cv2.copyMakeBorder(
                gray,
                self.padding, self.padding,
                self.padding, self.padding,
                cv2.BORDER_CONSTANT, value=255
            )

        result = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)

        if verbose:
            print(f"  Original: {image.shape} → Final: {result.shape}")

        self._steps = steps
        return result

    def _normalize_background(self, gray: np.ndarray) -> np.ndarray:
        """Ước lượng nền bằng morphological closing rồi chia (flat-field).

        Closing (dilate→erode) xóa nét chữ tối khỏi ảnh nền ước lượng mà không
        làm nền sáng lệch đi như dilate đơn thuần, nên ít tạo quầng ở biên chữ.
        """
        h, w = gray.shape

        ksize = max(h // 2, 15)
        ksize = min(ksize, 60, max(h - 2, 3), max(w - 2, 3))
        ksize = ksize if ksize % 2 == 1 else ksize + 1

        kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (ksize, ksize))
        bg = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, kernel)
        bg = cv2.GaussianBlur(bg, (0, 0), ksize / 4)

        gray_f = gray.astype(np.float32)
        bg_f = np.maximum(bg.astype(np.float32), 1.0)
        normalized = np.clip(gray_f / bg_f * 255.0, 0, 255).astype(np.uint8)
        return normalized

    def _contrast_stretch(self, gray: np.ndarray) -> np.ndarray:
        """Kéo giãn tuyến tính: percentile thấp (chữ đậm nhất) → đen,
        percentile cao (nền) → trắng. Bù việc phép chia nền làm chữ bạc màu,
        nhưng vẫn giữ thang xám liên tục (không nhị phân hóa)."""
        lo = float(np.percentile(gray, self.stretch_low_pct))
        hi = float(np.percentile(gray, self.stretch_high_pct))
        if hi - lo < 10:  # crop gần như trống → giữ nguyên
            return gray
        gray_f = (gray.astype(np.float32) - lo) / (hi - lo) * 255.0
        return np.clip(gray_f, 0, 255).astype(np.uint8)

    def _suppress_bleed(self, gray: np.ndarray) -> np.ndarray:
        """Đẩy các pixel xám nhạt (mực thấm từ mặt sau) về trắng bằng
        đường cong mềm quanh ngưỡng Otsu — không cắt cứng nên không phá
        biên chữ khử răng cưa."""
        t, _ = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
        knee = t + 0.3 * (255.0 - t)
        lut = np.arange(256, dtype=np.float32)
        a = np.clip((lut - t) / max(knee - t, 1.0), 0.0, 1.0)
        a = a * a * (3.0 - 2.0 * a)  # smoothstep
        lut = lut * (1.0 - a) + 255.0 * a
        return cv2.LUT(gray, lut.astype(np.uint8))

    def _sharpen(self, gray: np.ndarray) -> np.ndarray:
        amt = self.sharpen_amount
        blurred = cv2.GaussianBlur(gray, (0, 0), 1.0)
        sharpened = cv2.addWeighted(gray, 1.0 + amt, blurred, -amt, 0)
        return np.clip(sharpened, 0, 255).astype(np.uint8)

    def _binarize(self, gray: np.ndarray) -> np.ndarray:
        if self.binarize_method == "otsu":
            _, binary = cv2.threshold(
                gray, 0, 255,
                cv2.THRESH_BINARY + cv2.THRESH_OTSU
            )
        elif self.binarize_method == "adaptive":
            binary = cv2.adaptiveThreshold(
                gray, 255,
                cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                cv2.THRESH_BINARY,
                blockSize=15, C=8
            )
        elif self.binarize_method == "sauvola":
            binary = self._sauvola_threshold(gray)
        else:
            _, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

        binary = self._ensure_dark_text(binary)
        return binary

    def _sauvola_threshold(self, gray: np.ndarray,
                           window_size: int = None, k: float = 0.2) -> np.ndarray:
        h, w = gray.shape
        if window_size is None:
            ws = max(11, min(h // 2, 31))
            window_size = ws if ws % 2 == 1 else ws + 1

        gray_f = gray.astype(np.float64)
        R = 128.0

        mean = cv2.boxFilter(gray_f, -1, (window_size, window_size))
        mean_sq = cv2.boxFilter(gray_f**2, -1, (window_size, window_size))
        std = np.sqrt(np.maximum(mean_sq - mean**2, 0))

        threshold = mean * (1.0 + k * (std / R - 1.0))
        binary = np.where(gray_f <= threshold, 0, 255).astype(np.uint8)
        return binary

    def _ensure_dark_text(self, binary: np.ndarray) -> np.ndarray:
        black_pixels = np.sum(binary == 0)
        white_pixels = np.sum(binary == 255)

        if black_pixels > white_pixels:
            binary = cv2.bitwise_not(binary)
        return binary

    def _deskew(self, binary: np.ndarray) -> np.ndarray:
        h, w = binary.shape[:2]

        if h < 20 or w < 100:
            return binary

        try:
            inv = cv2.bitwise_not(binary)

            edges = cv2.Canny(inv, 50, 150, apertureSize=3)
            lines = cv2.HoughLinesP(
                edges, 1, np.pi/180,
                threshold=max(30, w//10),
                minLineLength=w//4,
                maxLineGap=20
            )

            if lines is None or len(lines) < 3:
                return binary

            angles = []
            for line in lines:
                x1, y1, x2, y2 = line[0]
                if abs(x2 - x1) > abs(y2 - y1):
                    angle = np.degrees(np.arctan2(y2 - y1, x2 - x1))
                    if abs(angle) < 10:
                        angles.append(angle)

            if not angles:
                return binary

            angle = float(np.median(angles))

            if abs(angle) < 0.5 or abs(angle) > 5:
                return binary

            center = (w // 2, h // 2)
            M = cv2.getRotationMatrix2D(center, angle, 1.0)
            rotated = cv2.warpAffine(
                binary, M, (w, h),
                flags=cv2.INTER_CUBIC,
                borderMode=cv2.BORDER_CONSTANT,
                borderValue=255
            )
            return rotated

        except Exception:
            return binary

    def _morph_clean(self, binary: np.ndarray) -> np.ndarray:
        h = binary.shape[0]

        if h < 30:
            return binary

        kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2, 2))

        cleaned = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)

        text_before = np.sum(binary == 0)
        text_after = np.sum(cleaned == 0)

        if text_after < text_before * 0.6:
            return binary

        return cleaned

    def get_steps(self) -> dict:
        return getattr(self, '_steps', {})


def compare_steps(image: np.ndarray, preprocessor: ImagePreprocessor,
                  save_path: str = None, title: str = "") -> np.ndarray:
    result = preprocessor.process(image, verbose=True)
    steps = preprocessor.get_steps()

    n = len(steps) + 1
    names = list(steps.keys()) + ["final"]
    imgs = list(steps.values()) + [cv2.cvtColor(result, cv2.COLOR_BGR2GRAY)]

    target_h = 80
    resized = []
    for img in imgs:
        if len(img.shape) == 3:
            img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        h, w = img.shape
        scale = target_h / h
        new_w = max(1, int(w * scale))
        r = cv2.resize(img, (new_w, target_h))
        resized.append(r)

    max_w = max(r.shape[1] for r in resized)
    label_h = 20
    cell_h = target_h + label_h + 4

    grid_rows = (n + 3) // 4
    grid_cols = min(n, 4)
    canvas_h = grid_rows * cell_h + 30
    canvas_w = grid_cols * (max_w + 10) + 10
    canvas = np.ones((canvas_h, canvas_w), dtype=np.uint8) * 200

    for idx, (name, img) in enumerate(zip(names, resized)):
        row = idx // 4
        col = idx % 4
        x = col * (max_w + 10) + 5
        y = row * cell_h + 25

        if name == "final":
            canvas[y-2:y+target_h+2, x-2:x+img.shape[1]+2] = 0
            canvas[y-1:y+target_h+1, x-1:x+img.shape[1]+1] = 200

        canvas[y:y+target_h, x:x+img.shape[1]] = img

        cv2.putText(canvas, name, (x, y-3),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.35, 30, 1)

    if title:
        cv2.putText(canvas, title, (5, 15),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, 0, 1)

    if save_path:
        cv2.imwrite(save_path, canvas)
        print(f"  Saved: {save_path}")

    return canvas


def test_with_rec(image: np.ndarray, preprocessor: ImagePreprocessor,
                  rec_model_dir: str = "./models/inference_rec"):
    try:
        from paddlex import create_predictor
        predictor = create_predictor(
            model_name='latin_PP-OCRv5_mobile_rec',
            model_dir=rec_model_dir
        )

        results_before = list(predictor.predict(image))
        text_before = results_before[0].get('rec_text', '') if results_before else ''
        score_before = results_before[0].get('rec_score', 0) if results_before else 0

        processed = preprocessor.process(image)
        results_after = list(predictor.predict(processed))
        text_after = results_after[0].get('rec_text', '') if results_after else ''
        score_after = results_after[0].get('rec_score', 0) if results_after else 0

        print(f"\n  Before: [{score_before:.4f}] {text_before}")
        print(f"  After:  [{score_after:.4f}] {text_after}")

        improvement = score_after - score_before
        if improvement > 0.01:
            print(f"  ✅ Improved: +{improvement:.4f}")
        elif improvement < -0.01:
            print(f"  ⚠️  Worse: {improvement:.4f}")
        else:
            print(f"  ➡️  Similar: {improvement:.4f}")

        return text_before, score_before, text_after, score_after

    except Exception as e:
        print(f"  Rec test skipped: {e}")
        return None, None, None, None


def main():
    parser = argparse.ArgumentParser(
        description="Image Preprocessor - Test tiền xử lý ảnh OCR "
                    "(test hàng loạt: dùng test_preprocessor.py)"
    )
    parser.add_argument("--image", required=True)
    parser.add_argument("--output", default="./output/preprocess_test")
    parser.add_argument("--binarize", action="store_true",
                        help="Bật nhị phân hóa (mặc định tắt)")
    parser.add_argument("--method", default="sauvola",
                        choices=["otsu", "adaptive", "sauvola"])
    parser.add_argument("--denoise", default=None,
                        choices=["bilateral", "gaussian", "nlm"],
                        help="Bật khử nhiễu (mặc định tắt)")
    parser.add_argument("--clahe", action="store_true",
                        help="Bật CLAHE (mặc định tắt)")
    parser.add_argument("--suppress_bleed", action="store_true",
                        help="Bật khử bleed-through mềm")
    parser.add_argument("--no_stretch", action="store_true")
    parser.add_argument("--no_sharpen", action="store_true")
    parser.add_argument("--compare", action="store_true",
                        help="Lưu ảnh so sánh từng bước")
    parser.add_argument("--test_rec", action="store_true")
    parser.add_argument("--rec_model", default="./models/inference_rec")
    args = parser.parse_args()

    os.makedirs(args.output, exist_ok=True)

    preprocessor = ImagePreprocessor(
        denoise=args.denoise is not None,
        denoise_method=args.denoise or "bilateral",
        clahe=args.clahe,
        contrast_stretch=not args.no_stretch,
        suppress_bleed=args.suppress_bleed,
        binarize=args.binarize,
        binarize_method=args.method,
        sharpen=not args.no_sharpen,
    )

    image = cv2.imread(args.image)
    if image is None:
        print(f"Cannot read: {args.image}")
        return

    stem = Path(args.image).stem
    result = preprocessor.process(image, verbose=True)
    out_path = os.path.join(args.output, f"{stem}_processed.jpg")
    cv2.imwrite(out_path, result)
    print(f"  Saved: {out_path}")

    if args.compare:
        compare_path = os.path.join(args.output, f"{stem}_compare.jpg")
        compare_steps(image, preprocessor, compare_path, title=stem)

    if args.test_rec:
        test_with_rec(image, preprocessor, args.rec_model)


if __name__ == "__main__":
    main()