#!/usr/bin/env python3 """Zoom into a region: upscale, stats, OCR.""" import sys, subprocess from PIL import Image import numpy as np path, x, y, w, h = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]), int(sys.argv[5]) scale = int(sys.argv[6]) if len(sys.argv) > 6 else 3 im = Image.open(path).convert("RGB") W, H = im.size x0, y0 = max(0, x), max(0, y) x1, y1 = min(W, x + w), min(H, y + h) crop = im.crop((x0, y0, x1, y1)) arr = np.asarray(crop).astype(float) print(f"region ({x0},{y0})-({x1},{y1}): mean RGB={arr.reshape(-1,3).mean(0).round(1)} " f"lum={0.2126*arr[...,0].mean()/255+0.7152*arr[...,1].mean()/255+0.0722*arr[...,2].mean()/255:.3f} " f"std={arr.std():.1f} max={arr.max():.0f}") # brightest structures: threshold above local background g = np.asarray(crop.convert("L")) for pct in (99, 99.9): print(f" p{pct} gray={np.percentile(g, pct):.0f}") big = crop.resize((crop.width * scale, crop.height * scale), Image.LANCZOS) big.save("/tmp/crop.png") p = subprocess.run(["tesseract", "/tmp/crop.png", "stdout", "-l", "eng+chi_sim", "--psm", "11"], capture_output=True, text=True) txt = [ln.strip() for ln in p.stdout.splitlines() if ln.strip() and len(ln.strip()) > 1] print("zoomed OCR:", txt if txt else "(nothing)")