bikramdocsumo
Initial release: SumoOCR tiny v0.1.0
10469c8
Raw History Blame Contribute Delete
12 kB
"""SumoOCR tiny: a page -> its text lines (detector + recognizer), or one line crop -> its text."""
from __future__ import annotations
import json
import os
from dataclasses import asdict, dataclass
from typing import Any, List, Optional, Sequence, Tuple, Union
import cv2
import numpy as np
from .backend import load_model
from .det import db_postprocess, det_input_size, level_quads, preprocess, sort_reading_order
from .rec import CTCDecoder, crop_line, recognize
MODEL_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")
@dataclass
class Line:
"""One text line: its text, mean character confidence (0-1) and box (4 [x, y] points, clockwise from the
top-left, in pixels of the input image)."""
text: str
conf: float
box: List[List[float]]
def to_dict(self) -> dict:
return asdict(self)
def _rotate(img: np.ndarray, deg: int) -> np.ndarray:
"""Turn the image clockwise by deg (90 / 180 / 270)."""
if deg == 90:
return cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
if deg == 180:
return cv2.rotate(img, cv2.ROTATE_180)
if deg == 270:
return cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)
return img
def _rotate_pts(q: np.ndarray, deg: int, h: int, w: int) -> np.ndarray:
"""Point coordinates after turning an h x w image clockwise by deg (same point order)."""
x, y = q[:, 0], q[:, 1]
if deg == 180:
return np.stack([w - x, h - y], 1).astype(np.float32)
if deg == 90:
return np.stack([h - y, x], 1).astype(np.float32)
if deg == 270:
return np.stack([y, w - x], 1).astype(np.float32)
return q
# after a turn by deg, the new tl, tr, br, bl are these points of _rotate_pts
_QUAD_ORDER = {180: [2, 3, 0, 1], 90: [3, 0, 1, 2], 270: [1, 2, 3, 0]}
def _rotate_quad(q: np.ndarray, deg: int, h: int, w: int) -> np.ndarray:
"""Box coordinates after turning an h x w image clockwise by deg (re-ordered tl, tr, br, bl)."""
if deg in _QUAD_ORDER:
return _rotate_pts(q, deg, h, w)[_QUAD_ORDER[deg]]
return q
class SumoOCR:
"""Page OCR with SumoOCR tiny.
ocr = SumoOCR() # ONNX Runtime on CPU; backend="openvino" needs `pip install sumoocr[openvino]`
lines = ocr("invoice.png") # a path, an H x W x 3 uint8 array (BGR, as cv2.imread) or a PIL image
text, conf = ocr.read_line(crop) # one line crop (any height)
The defaults are the settings the benchmarks were run with. max_side caps the long side of the page the detector
sees (1,280 px by default, automatically stepping up to 2,400 px on dense small print such as newspapers when
adaptive=True). text_score drops lines whose mean character confidence is below it. threads: CPU threads per model
(None = the runtime's default)."""
def __init__(self, backend: str = "onnxruntime", threads: Optional[int] = None, model_dir: str = MODEL_DIR,
det_model: Optional[str] = None, rec_model: Optional[str] = None,
max_side: int = 1280, min_side: int = 0, max_det_pixels: float = 6.0e6, det_thresh: float = 0.3,
box_thresh: float = 0.4, unclip_ratio: float = 1.6, text_score: float = 0.85, space_bias: float = 2.0,
box_level: float = 1.5, orient: bool = True, orient_conf: float = 0.92, orient_sample: int = 10,
adaptive: bool = True, adaptive_med_h: float = 13.0, adaptive_max_side: int = 2400, batch: int = 1):
if threads:
cv2.setNumThreads(int(threads))
cfg = json.load(open(os.path.join(model_dir, "config.json"), encoding="utf-8"))
self.height = int(cfg["H"])
det_path = det_model or os.path.join(model_dir, "det.onnx")
rec_path = rec_model or os.path.join(model_dir, "rec.onnx")
self.det = load_model(det_path, backend, threads, arena=True)
self.rec = load_model(rec_path, backend, threads, fix_height=self.height, arena=False)
with open(os.path.join(model_dir, "rec.classes.json"), encoding="utf-8") as fh:
self.decoder = CTCDecoder(json.load(fh), space_bias, case_conf=True, space_conf=True)
self.max_side, self.min_side, self.max_det_pixels = max_side, min_side, max_det_pixels
self.det_thresh, self.box_thresh, self.unclip_ratio = det_thresh, box_thresh, unclip_ratio
self.text_score, self.box_level, self.batch = text_score, box_level, batch
self.orient, self.orient_conf, self.orient_sample = orient, orient_conf, orient_sample
self.adaptive, self.adaptive_med_h, self.adaptive_max_side = adaptive, adaptive_med_h, adaptive_max_side
self._rgb = False
# ------------------------------------------------------------------ input
@staticmethod
def _load(image: Union[str, os.PathLike, np.ndarray, Any]) -> Tuple[np.ndarray, bool]:
"""-> (H x W x 3 uint8, is_rgb)"""
if isinstance(image, (str, os.PathLike)):
img = cv2.imdecode(np.fromfile(str(image), np.uint8), cv2.IMREAD_COLOR)
if img is None:
raise ValueError(f"cannot read image {image!s}")
return img, False
if not isinstance(image, np.ndarray): # PIL image
return np.asarray(image.convert("RGB")), True
if image.ndim == 2:
return cv2.cvtColor(image, cv2.COLOR_GRAY2BGR), False
if image.shape[2] == 4:
return cv2.cvtColor(image, cv2.COLOR_BGRA2BGR), False
return image, False
# -------------------------------------------------------------- detection
def _det_scale(self, h: int, w: int) -> float:
long_, short = max(h, w), min(h, w)
s = min(1.0, self.max_side / float(long_)) if self.max_side else 1.0
if self.min_side and short * s < self.min_side:
s = self.min_side / float(short)
if self.max_side and long_ * s > self.max_side * 1.5:
s = self.max_side * 1.5 / float(long_)
return s
def _detect_at(self, img: np.ndarray, scale: float) -> Tuple[List[np.ndarray], int, int]:
h, w = img.shape[:2]
nh, nw = det_input_size(h, w, scale, self.max_det_pixels)
prob = self.det(preprocess(img, nh, nw, self._rgb))[0, 0]
quads, _ = db_postprocess(prob, self.det_thresh, self.box_thresh, self.unclip_ratio)
out = []
sx, sy = w / float(nw), h / float(nh)
for q in quads:
q = q * np.array([sx, sy], np.float32)
q[:, 0] = np.clip(q[:, 0], 0, w - 1)
q[:, 1] = np.clip(q[:, 1], 0, h - 1)
if np.linalg.norm(q[0] - q[1]) > 3 and np.linalg.norm(q[0] - q[3]) > 3:
out.append(q)
return out, nh, nw
def _detect(self, img: np.ndarray) -> List[np.ndarray]:
h, w = img.shape[:2]
scale = self._det_scale(h, w)
out, nh, nw = self._detect_at(img, scale)
if self.adaptive and self.adaptive_med_h > 0 and len(out) >= 10 and self.max_side and \
self.adaptive_max_side > self.max_side and max(h, w) > self.max_side * 1.25:
s1 = nh / float(h)
hs = [min(float(np.linalg.norm(q[0] - q[1])), float(np.linalg.norm(q[0] - q[3]))) * s1 for q in out]
hs = [v for v in hs if v >= 3.0]
if len(hs) >= 10 and float(np.median(hs)) < self.adaptive_med_h:
s2 = min(1.0, self.adaptive_max_side / float(max(h, w)))
if s2 > scale * 1.15:
out, _, _ = self._detect_at(img, s2)
return out
# ------------------------------------------------------------ recognition
def _crops(self, img: np.ndarray, quads: Sequence[np.ndarray]) -> Tuple[List[np.ndarray], List[int]]:
crops, keep = [], []
for i, q in enumerate(quads):
cr = crop_line(img, q, self.height)
if cr is not None and cr.shape[1] >= 2:
crops.append(cr)
keep.append(i)
return crops, keep
def _read(self, crops: List[np.ndarray]) -> List[Tuple[str, float, float]]:
return recognize(self.rec, self.decoder, crops, batch=self.batch, rgb=self._rgb)
# ------------------------------------------------------------ orientation
@staticmethod
def _sideways(quads: Sequence[np.ndarray]) -> bool:
ratios = []
for q in quads:
w_q, h_q = np.linalg.norm(q[0] - q[1]), np.linalg.norm(q[0] - q[3])
if h_q > 0 and (w_q / h_q >= 1.5 or w_q / h_q <= 1 / 1.5):
ratios.append(w_q / h_q)
return len(ratios) >= 8 and sum(r < 1 for r in ratios) / len(ratios) > 0.5
def _sample(self, quads: Sequence[np.ndarray]) -> List[int]:
areas = [float(np.linalg.norm(q[0] - q[1]) * np.linalg.norm(q[0] - q[3])) for q in quads]
return sorted(range(len(quads)), key=lambda i: -areas[i])[: self.orient_sample]
def _flip_better(self, crops: List[np.ndarray]) -> bool:
"""True when the crops read better turned by 180 degrees."""
if not crops:
return False
a = self._read(crops)
b = self._read([np.ascontiguousarray(c[::-1, ::-1]) for c in crops])
wins = sum(rb[1] > ra[1] + 0.05 for ra, rb in zip(a, b))
return wins > len(crops) / 2 and np.mean([r[1] for r in b]) > np.mean([r[1] for r in a]) + 0.05
# -------------------------------------------------------------------- run
def __call__(self, image: Union[str, os.PathLike, np.ndarray, Any]) -> List[Line]:
"""The page's text lines in reading order."""
img, self._rgb = self._load(image)
h, w = img.shape[:2]
quads = self._detect(img)
rot = 0
if self.orient and self._sideways(quads): # text runs vertically: turn the page 90 or 270 degrees
crops, _ = self._crops(img, [quads[i] for i in self._sample(quads)])
rot = 90 if self._flip_better(crops) else 270
img = _rotate(img, rot)
h, w = img.shape[:2]
quads = self._detect(img)
crops, keep = self._crops(img, quads)
res = self._read(crops)
if self.orient and rot == 0 and res and float(np.median([r[1] for r in res])) < self.orient_conf:
idx = self._sample([quads[i] for i in keep])
if self._flip_better([crops[i] for i in idx]): # upside down
rot = 180
img = _rotate(img, 180)
quads = [_rotate_quad(q, 180, h, w) for q in quads]
crops, keep = self._crops(img, quads)
res = self._read(crops)
boxes = level_quads(quads, self.box_level) if self.box_level else quads
lines, upright = [], []
for k, i in enumerate(keep):
text, conf = res[k][0].strip(), res[k][1]
if not text or conf < self.text_score:
continue
q = boxes[i]
upright.append(q)
if rot: # boxes back in the input image's pixels
q = _rotate_quad(q, (360 - rot) % 360, h, w)
lines.append(Line(text, conf, [[float(x), float(y)] for x, y in q]))
return [lines[i] for i in sort_reading_order(upright)] # reading order on the upright page
def read_text(self, image: Union[str, os.PathLike, np.ndarray, Any]) -> str:
"""The page's text, one line per detected line, in reading order."""
return "\n".join(ln.text for ln in self(image))
def read_line(self, crop: Union[str, os.PathLike, np.ndarray, Any]) -> Tuple[str, float]:
"""One text-line crop (any size) -> (text, mean character confidence). No detection, no text_score filter."""
img, self._rgb = self._load(crop)
h, w = img.shape[:2]
line = cv2.resize(img, (max(1, int(round(w * self.height / float(h)))), self.height),
interpolation=cv2.INTER_AREA if h > self.height else cv2.INTER_CUBIC)
text, conf, _ = self._read([line])[0]
return text.strip(), conf