"""Text extraction from images with Tesseract OCR. Built by Noorullah Zamindar — original Flask app and notebook at https://github.com/NoorullahZamindar-007/Text-Extractor-From-Image This module is the OCR logic from the original project, kept unchanged in behaviour and packaged so it can be run without the Flask web server: * ``extract_text`` — the ``app.py`` behaviour: open an image and run ``pytesseract.image_to_string`` on it. The original app.py passed no config (Tesseract defaults); the notebook demonstrated ``-l eng --oem 3 --psm 6``, which this module uses as the default because it performs better on blocks of text — pass ``config=""`` to reproduce app.py exactly. * ``extract_text_preprocessed`` — the same OCR, after the notebook's preprocessing helpers (grayscale, median denoise, Otsu threshold, deskew), which help on noisy or slightly rotated scans. * The notebook's preprocessing helpers themselves: ``get_grayscale``, ``remove_noise``, ``thresholding``, ``deskew`` (plus ``erode``, ``opening`` and ``canny``, kept for completeness). * ``word_boxes`` / ``word_data`` — the notebook's bounding-box and word-level-confidence helpers. There are no trained weights here: the "model" is Tesseract OCR (``tesseract-ocr``, language data ``eng``), driven by this code. Tesseract must be installed on the machine (``apt install tesseract-ocr`` on Debian/Ubuntu) and the ``eng`` language data present. """ import os import sys import cv2 import numpy as np import pytesseract from PIL import Image from pytesseract import Output # The original app.py hard-coded the Windows Tesseract path. Only do that # on Windows; everywhere else Tesseract is found on PATH. if sys.platform.startswith("win"): pytesseract.pytesseract.tesseract_cmd = ( r"C:\Program Files\Tesseract-OCR\tesseract.exe" ) DEFAULT_CONFIG = r"-l eng --oem 3 --psm 6" # --------------------------------------------------------------------------- # Core extraction — the app.py behaviour # --------------------------------------------------------------------------- def extract_text(image_path, config=DEFAULT_CONFIG, lang="eng"): """Extract text from an image file, exactly as the original app.py does. Returns the raw string Tesseract produces (trailing form feed included). """ img = Image.open(image_path) return pytesseract.image_to_string(img, lang=lang, config=config) def extract_text_preprocessed(image_path, steps=("grayscale", "denoise", "threshold"), config=DEFAULT_CONFIG, lang="eng"): """Extract text after the notebook's preprocessing pipeline. ``steps`` picks from "grayscale", "denoise", "threshold", "deskew". The default (grayscale + denoise + Otsu threshold) is the pipeline the notebook builds up in cells 9-11. Deskew is off by default: it only helps on rotated scans and can hurt clean images. """ image = cv2.imread(image_path) if image is None: raise ValueError(f"could not read image: {image_path}") processed = preprocess(image, steps) return pytesseract.image_to_string( Image.fromarray(processed), lang=lang, config=config) def preprocess(image, steps=("grayscale", "denoise", "threshold")): """Apply the notebook's preprocessing helpers, in the given order.""" out = image for step in steps: if step == "grayscale": out = get_grayscale(out) elif step == "denoise": out = remove_noise(out) elif step == "threshold": out = thresholding(out) elif step == "deskew": out = deskew(out) else: raise ValueError(f"unknown preprocessing step: {step}") return out # --------------------------------------------------------------------------- # Preprocessing helpers — from the notebook, unchanged # --------------------------------------------------------------------------- def get_grayscale(image): return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) def remove_noise(image): return cv2.medianBlur(image, 5) def thresholding(image): return cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1] def erode(image): kernel = np.ones((5, 5), np.uint8) return cv2.erode(image, kernel, iterations=1) def opening(image): kernel = np.ones((5, 5), np.uint8) return cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel) def canny(image): return cv2.Canny(image, 100, 200) def deskew(image): coords = np.column_stack(np.where(image > 0)) angle = cv2.minAreaRect(coords)[-1] if angle < -45: angle = -(90 + angle) else: angle = -angle (h, w) = image.shape[:2] center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, angle, 1.0) rotated = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE) return rotated # --------------------------------------------------------------------------- # Word-level output — from the notebook (cells 17-18) # --------------------------------------------------------------------------- def word_boxes(image_path): """Draw a green box around every character Tesseract finds. Returns the annotated image as a numpy array (BGR), like the notebook. """ img = cv2.imread(image_path) h, w, _ = img.shape boxes = pytesseract.image_to_boxes(img) for b in boxes.splitlines(): b = b.split(" ") img = cv2.rectangle(img, (int(b[1]), h - int(b[2])), (int(b[3]), h - int(b[4])), (0, 255, 0), 2) return img def word_data(image_path, min_conf=60): """Word-level OCR data (text, confidence, box) for every detected word. Returns the dict ``pytesseract.image_to_data`` produces. """ img = cv2.imread(image_path) return pytesseract.image_to_data(img, output_type=Output.DICT) def find_word(image_path, pattern, min_conf=60): """Draw a green box around words matching ``pattern`` (regex). Mirrors notebook cell 18, which searched for the word "artificially". Returns the annotated image as a numpy array (BGR). """ import re img = cv2.imread(image_path) d = word_data(image_path) n_boxes = len(d["text"]) for i in range(n_boxes): if int(d["conf"][i]) > min_conf: if re.match(pattern, d["text"][i]): (x, y, w, h) = (d["left"][i], d["top"][i], d["width"][i], d["height"][i]) img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) return img # --------------------------------------------------------------------------- # CLI # --------------------------------------------------------------------------- def main(argv=None): import argparse parser = argparse.ArgumentParser( description="Extract text from an image with Tesseract OCR.") parser.add_argument("image", help="image file to read") parser.add_argument("--preprocess", action="store_true", help="run the notebook preprocessing first " "(grayscale + denoise + Otsu threshold)") parser.add_argument("--deskew", action="store_true", help="also deskew (only useful on rotated scans)") parser.add_argument("--config", default=DEFAULT_CONFIG, help="Tesseract config string") args = parser.parse_args(argv) if args.preprocess: steps = ["grayscale", "denoise", "threshold"] if args.deskew: steps.append("deskew") print(extract_text_preprocessed(args.image, steps=steps, config=args.config), end="") else: print(extract_text(args.image, config=args.config), end="") return 0 if __name__ == "__main__": raise SystemExit(main())