Spaces:
Sleeping
Sleeping
File size: 871 Bytes
835eeaa | 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 | 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
|