Spaces:
Sleeping
Sleeping
Download ocr/image_utils.py from afueth/malayalam-ocr: direct link, hf CLI and curl.
- Browser
- Download file 871 Bytes
-
https://huggingface.co/spaces/afueth/malayalam-ocr/resolve/main/ocr/image_utils.py
- Command line
-
hf download hf://spaces/afueth/malayalam-ocr/ocr/image_utils.py
-
curl -L -o image_utils.py https://huggingface.co/spaces/afueth/malayalam-ocr/resolve/main/ocr/image_utils.py
871 Bytes
| 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 | |