"""Text-line recognition: crop from the full-resolution page, resize to the recognizer height, greedy CTC decode.""" from __future__ import annotations import math from typing import List, Optional, Sequence, Tuple import cv2 import numpy as np def crop_line(img: np.ndarray, quad: np.ndarray, height: int) -> Optional[np.ndarray]: """Perspective-rectify `quad` (tl, tr, br, bl in page pixels) to a `height`-px uint8 crop (same channel order as img). Shrinking first resizes the region with INTER_AREA, then warps at the reduced scale. Tall crops (h / w >= 1.5) are turned 90 degrees counter-clockwise.""" q = quad.astype(np.float32) w_q = max(np.linalg.norm(q[0] - q[1]), np.linalg.norm(q[2] - q[3])) h_q = max(np.linalg.norm(q[0] - q[3]), np.linalg.norm(q[1] - q[2])) if w_q < 2 or h_q < 2: return None vertical = h_q / w_q >= 1.5 H, W = img.shape[:2] x0 = max(0, int(math.floor(q[:, 0].min())) - 1) y0 = max(0, int(math.floor(q[:, 1].min())) - 1) x1 = min(W, int(math.ceil(q[:, 0].max())) + 2) y1 = min(H, int(math.ceil(q[:, 1].max())) + 2) if x1 - x0 < 2 or y1 - y0 < 2: return None region = img[y0:y1, x0:x1] q = q - np.array([x0, y0], np.float32) f = height / (w_q if vertical else h_q) out_w, out_h = max(1, int(round(w_q * f))), max(1, int(round(h_q * f))) if f < 0.75: rw, rh = max(1, int(round(region.shape[1] * f))), max(1, int(round(region.shape[0] * f))) region = cv2.resize(region, (rw, rh), interpolation=cv2.INTER_AREA) q = q * np.array([rw / (x1 - x0), rh / (y1 - y0)], np.float32) interp = cv2.INTER_LINEAR else: interp = cv2.INTER_CUBIC dst = np.array([[0, 0], [out_w, 0], [out_w, out_h], [0, out_h]], np.float32) crop = cv2.warpPerspective(region, cv2.getPerspectiveTransform(q, dst), (out_w, out_h), flags=interp, borderMode=cv2.BORDER_REPLICATE) if vertical: crop = np.ascontiguousarray(np.rot90(crop)) if crop.shape[0] != height: crop = cv2.resize(crop, (max(1, int(round(crop.shape[1] * height / crop.shape[0]))), height), interpolation=cv2.INTER_LINEAR) return crop class CTCDecoder: """Greedy CTC decoding. space_bias > 1 multiplies the space class's probability before the argmax (the recognizer drops spaces more often than it invents them); confidences stay the unbiased probabilities. case_conf: a letter's confidence also counts its other case (C / c, O / o, S / s look alike). space_conf: a space's confidence also counts the blank (a biased space starts on a frame where it is at most 0.5).""" def __init__(self, classes: Sequence[str], space_bias: float = 2.0, case_conf: bool = True, space_conf: bool = True): self.classes = list(classes) self.lut = np.array(self.classes, dtype=object) self.space_bias = float(space_bias) self.space_idx = len(self.classes) - 1 if self.classes[-1] == " " else ( self.classes.index(" ") if " " in self.classes else -1) pos = {ch: i for i, ch in enumerate(self.classes) if i} self.case_pair = np.array([pos.get(ch.swapcase(), -1) if i and len(ch) == 1 and ch.swapcase() != ch else -1 for i, ch in enumerate(self.classes)], np.int64) if case_conf else None self.space_conf = bool(space_conf) and self.space_idx > 0 def __call__(self, probs: np.ndarray, valid: Optional[Sequence[int]] = None) -> List[Tuple[str, float, float]]: """probs: N x T x C softmax; valid[i] = time steps of sample i inside the real crop. -> (text, mean character confidence, min character confidence) per sample.""" if self.space_bias != 1.0 and self.space_idx >= 0: idx = probs.argmax(axis=2) pmax = np.take_along_axis(probs, idx[:, :, None], axis=2)[:, :, 0] sp = probs[:, :, self.space_idx] pick_sp = (sp * self.space_bias) > pmax idx = np.where(pick_sp, self.space_idx, idx) pmax = np.where(pick_sp, sp, pmax) else: idx = probs.argmax(axis=2) pmax = probs.max(axis=2) if self.case_pair is not None: pair = self.case_pair[idx] pmax = np.minimum(1.0, pmax + np.where( pair >= 0, np.take_along_axis(probs, np.maximum(pair, 0)[:, :, None], axis=2)[:, :, 0], 0.0)) if self.space_conf: pmax = np.where(idx == self.space_idx, np.minimum(1.0, pmax + probs[:, :, 0]), pmax) out = [] for i in range(probs.shape[0]): t, p = idx[i], pmax[i] if valid is not None: t, p = t[: valid[i]], p[: valid[i]] sel = np.ones(len(t), dtype=bool) sel[1:] = t[1:] != t[:-1] sel &= t != 0 if not sel.any(): out.append(("", 0.0, 0.0)) continue ps = p[sel] out.append(("".join(self.lut[t[sel]]), float(ps.mean()), float(ps.min()))) return out def recognize(model, decoder: CTCDecoder, crops: List[np.ndarray], batch: int = 1, stride: int = 8, rgb: bool = False) -> List[Tuple[str, float, float]]: """Read crops (all the same height). Sorted by width and batched with mid-grey right padding to the batch's widest crop (rounded up to `stride`); time steps in the padding are ignored. batch=1 reads every line alone (the recognizer attends over the whole line, so padding moves its outputs a little).""" n = len(crops) res: List[Tuple[str, float, float]] = [("", 0.0, 0.0)] * n if n == 0: return res order = sorted(range(n), key=lambda i: (crops[i].shape[1], i)) h = crops[0].shape[0] src = (2, 1, 0) if rgb else (0, 1, 2) for s in range(0, n, max(1, int(batch))): ids = order[s:s + max(1, int(batch))] wpad = int(math.ceil(max(crops[i].shape[1] for i in ids) / stride) * stride) xb = np.zeros((len(ids), 3, h, wpad), np.float32) valid = [] for k, i in enumerate(ids): c = crops[i] for ch in range(3): xb[k, ch, :, :c.shape[1]] = c[:, :, src[ch]] valid.append(int(math.ceil(c.shape[1] / stride))) xb *= 2.0 / 255.0 xb -= 1.0 for k, i in enumerate(ids): xb[k, :, :, crops[i].shape[1]:] = 0.0 probs = model(xb) T = probs.shape[1] scale = T / float(wpad) valid = [min(T, int(math.ceil(v * stride * scale))) for v in valid] for k, r in zip(ids, decoder(probs, valid)): res[k] = r return res