File size: 6,666 Bytes
10469c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
"""Text detection: input scaling, DB post-processing, reading order, box levelling (PP-OCRv6 tiny detector)."""
from __future__ import annotations

import math
from typing import List, Tuple

import cv2
import numpy as np

MEAN = STD = np.array([0.5, 0.5, 0.5], np.float32)  # detector input: (x / 255 - 0.5) / 0.5, BGR


def det_input_size(h: int, w: int, scale: float, max_pixels: float) -> Tuple[int, int]:
    """(nh, nw): multiples of 32 near (h * scale, w * scale), capped at max_pixels."""
    if max_pixels and h * w * scale * scale > max_pixels:
        scale = math.sqrt(max_pixels / float(h * w))
    return max(32, int(round(h * scale / 32.0)) * 32), max(32, int(round(w * scale / 32.0)) * 32)


def preprocess(img: np.ndarray, nh: int, nw: int, rgb: bool = False) -> np.ndarray:
    """Page (BGR, or RGB when rgb=True) -> 1 x 3 x nh x nw float32 in the detector's BGR order."""
    return cv2.dnn.blobFromImage(img, scalefactor=2.0 / 255.0, size=(nw, nh), mean=(127.5, 127.5, 127.5),
                                 swapRB=rgb, crop=False)


def _order_quad(pts: np.ndarray) -> np.ndarray:
    """4 points -> top-left, top-right, bottom-right, bottom-left."""
    pts = pts[np.argsort(pts[:, 0], kind="stable")]
    left, right = pts[:2], pts[2:]
    tl, bl = (left[0], left[1]) if left[0][1] <= left[1][1] else (left[1], left[0])
    tr, br = (right[0], right[1]) if right[0][1] <= right[1][1] else (right[1], right[0])
    return np.array([tl, tr, br, bl], dtype=np.float32)


def db_postprocess(prob: np.ndarray, thresh: float = 0.3, box_thresh: float = 0.5, unclip_ratio: float = 1.6,
                   max_candidates: int = 5000, min_size: float = 3.0) -> Tuple[List[np.ndarray], List[float]]:
    """DB probability map (H x W) -> quads (map pixels) and box scores: binarize, 2 x 2 dilation, contours,
    minAreaRect, mean probability inside the box, unclip. Unclipping a w x h rectangle by
    d = area * ratio / perimeter is done analytically (the (w + 2d) x (h + 2d) rectangle, same centre and angle)."""
    bitmap = cv2.dilate((prob > thresh).astype(np.uint8), np.ones((2, 2), np.uint8))
    contours, _ = cv2.findContours(bitmap, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    H, W = prob.shape
    quads: List[np.ndarray] = []
    scores: List[float] = []
    for cnt in contours[:max_candidates]:
        (cx, cy), (rw, rh), ang = cv2.minAreaRect(cnt)
        if min(rw, rh) < min_size:
            continue
        pts = cv2.boxPoints(((cx, cy), (rw, rh), ang))
        xmin = int(np.clip(np.floor(pts[:, 0].min()), 0, W - 1))
        xmax = int(np.clip(np.ceil(pts[:, 0].max()), 0, W - 1))
        ymin = int(np.clip(np.floor(pts[:, 1].min()), 0, H - 1))
        ymax = int(np.clip(np.ceil(pts[:, 1].max()), 0, H - 1))
        mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), np.uint8)
        q = pts.copy()
        q[:, 0] -= xmin
        q[:, 1] -= ymin
        cv2.fillPoly(mask, [q.astype(np.int32)], 1)
        score = cv2.mean(prob[ymin:ymax + 1, xmin:xmax + 1], mask)[0]
        if score < box_thresh:
            continue
        d = rw * rh * unclip_ratio / (2.0 * (rw + rh))
        nw_, nh_ = rw + 2 * d, rh + 2 * d
        if min(nw_, nh_) < min_size + 2:
            continue
        quads.append(_order_quad(cv2.boxPoints(((cx, cy), (nw_, nh_), ang))))
        scores.append(float(score))
    return quads, scores


def sort_reading_order(quads: List[np.ndarray], y_tol: float = 0.5) -> List[int]:
    """Indices top to bottom, then left to right within a line (a box joins the current line when its centre is
    within y_tol x the line's height of the line's)."""
    if not quads:
        return []
    cy = [float(q[:, 1].mean()) for q in quads]
    hh = [max(1.0, float(q[:, 1].max() - q[:, 1].min())) for q in quads]
    cx = [float(q[:, 0].min()) for q in quads]
    lines: List[List[int]] = []
    ref = None
    for i in sorted(range(len(quads)), key=lambda i: (cy[i], cx[i])):
        if lines and abs(cy[i] - ref[0]) <= y_tol * ref[1]:
            lines[-1].append(i)
        else:
            lines.append([i])
            ref = (cy[i], hh[i])
    return [i for ln in lines for i in sorted(ln, key=lambda j: cx[j])]


def _mod90(a: float) -> float:
    return (a + 45.0) % 90.0 - 45.0


def level_quads(quads: List[np.ndarray], max_growth: float, min_deg: float = 1.0, ref_lines: int = 3,
                neighbours: int = 10, square: float = 1.5) -> List[np.ndarray]:
    """Returned boxes with the odd tilted ones levelled (output only: lines are read from the original boxes).
    A box more than min_deg off both the page angle and the length-weighted median angle of its nearest line-like
    neighbours is replaced by its bounding rectangle along that angle, when the rectangle is at most max_growth x its
    area (mixed-size glyphs, e.g. a small field number before a large letter, tilt minAreaRect boxes)."""
    if max_growth <= 0 or len(quads) < ref_lines:
        return list(quads)
    q = np.array(quads, np.float64)
    e1, e2 = q[:, 1] - q[:, 0], q[:, 3] - q[:, 0]
    l1, l2 = np.hypot(e1[:, 0], e1[:, 1]), np.hypot(e2[:, 0], e2[:, 1])
    ang = np.array([_mod90(math.degrees(math.atan2(y, x))) for x, y in e1])
    cen = q.mean(axis=1)
    lines = np.flatnonzero(np.maximum(l1, l2) >= 3.0 * np.minimum(l1, l2))
    if len(lines) < ref_lines:
        return list(quads)
    page = float(np.median(ang[lines]))
    out = list(quads)
    for i in np.flatnonzero([abs(_mod90(a - page)) > min_deg for a in ang]):
        near = lines[np.argsort(((cen[lines] - cen[i]) ** 2).sum(axis=1))]
        near = near[near != i][:neighbours]
        off = np.array([_mod90(a - page) for a in ang[near]])
        o = np.argsort(off)
        cum = np.cumsum(np.maximum(l1, l2)[near][o])
        ref = page + float(off[o][np.searchsorted(cum, cum[-1] / 2.0)])
        if abs(_mod90(ang[i] - ref)) <= min_deg:
            continue
        t = math.radians(ref)
        u, v = np.array([math.cos(t), math.sin(t)]), np.array([-math.sin(t), math.cos(t)])
        s, r = q[i] @ u, q[i] @ v
        if max(l1[i], l2[i]) < square * min(l1[i], l2[i]):  # one glyph: no text direction, level it in place
            cs, cr = cen[i] @ u, cen[i] @ v
            s, r = np.array([cs - l1[i] / 2, cs + l1[i] / 2]), np.array([cr - l2[i] / 2, cr + l2[i] / 2])
        elif (s.max() - s.min()) * (r.max() - r.min()) > max_growth * l1[i] * l2[i]:
            continue
        out[i] = _order_quad(np.array([s0 * u + r0 * v for s0, r0 in
                                       ((s.min(), r.min()), (s.max(), r.min()), (s.max(), r.max()), (s.min(), r.max()))],
                                      np.float32))
    return out