File size: 5,596 Bytes
f0174d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
"""Route-A production engine, shard 3/4.
Copied verbatim from routeA_pilot/ncc_engine.py + inkbox.py, plus a
multi-peak extractor needed for the column-wise monotone DP (recipe #5).
"""
import numpy as np
from PIL import Image


def _fast_len(n):
    best = 2 * n
    p5 = 1
    while p5 < best:
        p3 = p5
        while p3 < best:
            p2 = p3
            while p2 < n:
                p2 *= 2
            if p2 < best:
                best = p2
            p3 *= 3
        p5 *= 5
    return best


class ImgCtx:
    """FFT numerator + integral-image denominator, image transform cached."""

    def __init__(self, img):
        img = np.asarray(img, dtype=np.float64)
        self.H, self.W = img.shape
        self.Hf, self.Wf = _fast_len(self.H), _fast_len(self.W)
        pad = np.zeros((self.Hf, self.Wf))
        pad[:self.H, :self.W] = img
        # complex64 spectrum: halves memory and FFT time; the denominator stays
        # float64 (it needs the cancellation headroom of s2 - s1^2/n).
        self.F = np.fft.rfft2(pad.astype(np.float32))
        ii = np.zeros((self.H + 1, self.W + 1))
        ii2 = np.zeros((self.H + 1, self.W + 1))
        np.cumsum(np.cumsum(img, 0), 1, out=ii[1:, 1:])
        np.cumsum(np.cumsum(img * img, 0), 1, out=ii2[1:, 1:])
        self.ii, self.ii2 = ii, ii2
        del pad

    def ncc(self, tpl):
        """valid-mode NCC map.  Bit-identical to the pilot's ncc() (verified
        max|diff| = 0); the template transform is done in two stages so only
        the h non-zero rows are row-transformed, and the denominator is built
        in place -- 1.4x faster, same numbers."""
        h, w = tpl.shape
        if h > self.H or w > self.W:
            return None
        tz = tpl - tpl.mean()
        tnorm = float(np.sqrt((tz * tz).sum()))
        if tnorm < 1e-8:
            return None
        T1 = np.fft.rfft(tz.astype(np.float32), n=self.Wf, axis=1)
        Tp = np.zeros((self.Hf, T1.shape[1]), dtype=np.complex64)
        Tp[:h] = T1
        G = np.fft.fft(Tp, axis=0)
        np.conj(G, out=G)
        G *= self.F
        corr = np.fft.irfft2(G, s=(self.Hf, self.Wf))
        ny, nx = self.H - h + 1, self.W - w + 1
        num = corr[:ny, :nx]
        ii, ii2 = self.ii, self.ii2
        s1 = ii[h:h + ny, w:w + nx] - ii[0:ny, w:w + nx] - ii[h:h + ny, 0:nx] + ii[0:ny, 0:nx]
        var = ii2[h:h + ny, w:w + nx] - ii2[0:ny, w:w + nx] - ii2[h:h + ny, 0:nx] + ii2[0:ny, 0:nx]
        n = h * w
        s1 *= s1
        s1 /= n
        var -= s1
        np.clip(var, 0, None, out=var)
        # Degenerate-window guard.  The pilot's `denom > 1e-8` is not a real
        # floor: a window of blank paper has local variance ~0 (exactly 0 after
        # decimation), so the numerator's FFT round-off gets divided by almost
        # nothing and clips to NCC = 1.0 -- a phantom perfect match on empty
        # paper.  Require instead that the window carry actual contrast:
        # local sd > 0.5 grey level AND > 1% of the template's sd.
        ok = var > max(0.25 * n, 1e-4 * tnorm * tnorm)
        np.sqrt(var, out=var)
        var *= tnorm
        var = var.astype(np.float32)
        out = np.zeros_like(num)
        np.divide(num, var, out=out, where=ok)
        np.clip(out, -1.0, 1.0, out=out)
        return out


def load_gray(path):
    return np.asarray(Image.open(path).convert('L'), dtype=np.float64)


def resize_tpl(pil_gray, s):
    w, h = pil_gray.size
    nw, nh = max(4, int(round(w * s))), max(4, int(round(h * s)))
    return np.asarray(pil_gray.resize((nw, nh), Image.LANCZOS), dtype=np.float64)


def top_peaks(m, th, tw, k=6):
    """Top-k spatially separated peaks of a valid-mode NCC map.
    Block-max NMS on cells of half template size, then refine inside the cell."""
    H, W = m.shape
    by = max(4, th // 2)
    bx = max(4, tw // 2)
    ny = (H + by - 1) // by
    nx = (W + bx - 1) // bx
    pad = np.full((ny * by, nx * bx), -2.0, dtype=m.dtype)
    pad[:H, :W] = m
    blocks = pad.reshape(ny, by, nx, bx).max(axis=(1, 3))
    flat = blocks.ravel()
    cand = np.argsort(flat)[::-1][:60]
    used = np.zeros((ny, nx), bool)
    out = []
    for idx in cand:
        cy, cx = divmod(int(idx), nx)
        if used[max(0, cy - 1):cy + 2, max(0, cx - 1):cx + 2].any():
            continue
        sub = m[cy * by:min(H, (cy + 1) * by), cx * bx:min(W, (cx + 1) * bx)]
        if sub.size == 0:
            continue
        j = int(np.argmax(sub))
        yy, xx = divmod(j, sub.shape[1])
        out.append((float(sub[yy, xx]), int(cx * bx + xx), int(cy * by + yy)))
        used[cy, cx] = True
        if len(out) >= k:
            break
    return out


def ink_bbox_arr(g, frac=0.03):
    """verbatim from routeA_pilot/inkbox.py"""
    h, w = g.shape
    bg = np.percentile(g, 85)
    thr = bg - 0.45 * (bg - np.percentile(g, 2))
    m = g < thr
    cs = m.sum(0).astype(float)
    rs = m.sum(1).astype(float)
    if cs.max() < 1 or rs.max() < 1:
        return (0, 0, w, h), 0
    def span(p):
        t = max(1.0, frac * p.max())
        idx = np.where(p >= t)[0]
        return int(idx[0]), int(idx[-1]) + 1
    x0, x1 = span(cs)
    y0, y1 = span(rs)
    if x1 - x0 < 4: x0, x1 = 0, w
    if y1 - y0 < 4: y0, y1 = 0, h
    return (x0, y0, x1, y1), int(m[y0:y1, x0:x1].sum())


def iou(a, b):
    ax, ay, aw, ah = a[0], a[1], a[2] - a[0], a[3] - a[1]
    bx, by, bw, bh = b[0], b[1], b[2] - b[0], b[3] - b[1]
    ix = max(0.0, min(ax + aw, bx + bw) - max(ax, bx))
    iy = max(0.0, min(ay + ah, by + bh) - max(ay, by))
    it = ix * iy
    return it / (aw * ah + bw * bh - it + 1e-9)