File size: 1,958 Bytes
26b8deb | 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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | """OCR processing using Tesseract and Pillow."""
from __future__ import annotations
import io
import logging
from typing import Optional
try:
from PIL import Image, ImageEnhance, ImageFilter
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
try:
import pytesseract
TESSERACT_AVAILABLE = True
except ImportError:
TESSERACT_AVAILABLE = False
logger = logging.getLogger(__name__)
def preprocess_image_for_ocr(image: "Image.Image") -> "Image.Image":
"""Enhance image for better OCR accuracy."""
img = image.convert("L")
enhancer = ImageEnhance.Contrast(img)
img = enhancer.enhance(2.0)
img = img.filter(ImageFilter.SHARPEN)
w, h = img.size
if w < 1000:
scale = 1000 / w
img = img.resize((int(w * scale), int(h * scale)), Image.LANCZOS)
return img
def ocr_image(image: "Image.Image", lang: str = "eng") -> str:
"""Run Tesseract OCR on a PIL Image."""
if not PIL_AVAILABLE:
raise RuntimeError("Pillow is not installed. Install it with: pip install pillow")
if not TESSERACT_AVAILABLE:
raise RuntimeError("pytesseract is not installed. Install it with: pip install pytesseract")
processed = preprocess_image_for_ocr(image)
config = "--oem 3 --psm 6"
text = pytesseract.image_to_string(processed, lang=lang, config=config)
return text.strip()
def ocr_image_file(path: str, lang: str = "eng") -> str:
"""OCR an image file by path."""
if not PIL_AVAILABLE:
raise RuntimeError("Pillow is not installed.")
with Image.open(path) as img:
img = img.convert("RGB")
return ocr_image(img, lang=lang)
def ocr_image_bytes(data: bytes, lang: str = "eng") -> str:
"""OCR image from raw bytes."""
if not PIL_AVAILABLE:
raise RuntimeError("Pillow is not installed.")
with Image.open(io.BytesIO(data)) as img:
img = img.convert("RGB")
return ocr_image(img, lang=lang)
|