Download image_preprocessor.py from sirimiri/VOCR: direct link, hf CLI and curl.
- Browser
- Download file 17.7 kB
-
https://huggingface.co/spaces/sirimiri/VOCR/resolve/main/image_preprocessor.py
- Command line
-
hf download hf://spaces/sirimiri/VOCR/image_preprocessor.py
-
curl -L -o image_preprocessor.py https://huggingface.co/spaces/sirimiri/VOCR/resolve/main/image_preprocessor.py
17.7 kB
| """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() | |