File size: 1,134 Bytes
af24ae8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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")