alirezaaminzadeh's picture
Upload folder using huggingface_hub
af24ae8 verified
Raw
History Blame Contribute Delete
1.13 kB
"""Image preprocessing to improve OCR accuracy."""
from __future__ import annotations
import numpy as np
from PIL import Image, ImageEnhance, ImageOps
def preprocess_for_ocr(image: Image.Image, max_width: int = 1600) -> Image.Image:
"""Enhance contrast and resize for better OCR on scanned invoices."""
img = image.convert("RGB")
if img.width > max_width:
ratio = max_width / img.width
img = img.resize((max_width, int(img.height * ratio)), Image.Resampling.LANCZOS)
gray = ImageOps.grayscale(img)
enhanced = ImageEnhance.Contrast(gray).enhance(1.6)
sharpened = ImageEnhance.Sharpness(enhanced).enhance(1.3)
return sharpened.convert("RGB")
def deskew_estimate(image: Image.Image) -> Image.Image:
"""Light deskew using numpy — skip heavy CV deps."""
arr = np.array(image.convert("L"))
if arr.size == 0:
return image
# Normalize brightness
p5, p95 = np.percentile(arr, [5, 95])
if p95 > p5:
arr = np.clip((arr - p5) * 255.0 / (p95 - p5), 0, 255).astype(np.uint8)
return Image.fromarray(arr).convert("RGB")