from __future__ import annotations from PIL import Image, ImageOps, ImageEnhance def preprocess_image( img: Image.Image, grayscale: bool = True, contrast: float = 2.0, threshold: int | None = 160, invert: bool = False, ) -> Image.Image: """ Simple preprocessing for printed text. - grayscale + boost contrast - optional thresholding - optional invert (useful if white text on dark bg) """ img = ImageOps.exif_transpose(img) # fix phone rotation if grayscale: img = img.convert("L") else: img = img.convert("RGB") if contrast and contrast != 1.0: img = ImageEnhance.Contrast(img).enhance(float(contrast)) if threshold is not None: t = int(threshold) img = img.point(lambda p: 255 if p > t else 0) if invert: img = ImageOps.invert(img) return img