qr-scan-difficulty-check / server /quality_fit.py
devmandan's picture
Fix styled-file hints, and add inches, copies and the many-codes rule
a59c3c4 verified
Raw History Blame Contribute Delete
17 kB
"""The measuring behind quality.py: sampling the code through its corners, the finder-pattern fits, the levels of the
code's regions and the quiet zone. Pure functions, numpy and OpenCV only.
Module coordinates (u, v) run along the code as drawn, in squares: (0, 0) its outer top-left corner, (n, n) the
bottom-right. A homography h maps them to the frame's pixels (pixel centres at whole numbers).
"""
from __future__ import annotations
import math
import cv2
import numpy as np
U = np.arange(-10, 81) / 10 # along a finder profile, squares from its outer edge: -1 .. 8
EDGES = np.array([-1.0, -0.5, 0, 1, 2, 5, 6, 7, 8]) # the window's ends, the margin square's halves and the
# 1:1:3:1:1 pattern's edges
S_GRID = 0.01 * 1.25 ** np.arange(22) # blur candidates in squares, 0.01 .. 1.1
D_GRID = np.arange(-5, 6) * 0.1 # the finder's offset against the corners, in squares
FIT_RMS, MIN_STEP, S_MAX = 0.12, 8.0, 1.0 # a profile counts if its residual is under 12% of its step
QZ_STEPS = 0.125 + np.arange(16) * 0.25 # quiet-zone lines, squares out from the symbol: 0.125 .. 3.875; a
# margin is reported halfway between its last clear line and the next
QZ_TOWARD, QZ_SHARE = 0.4, 0.05 # a point intrudes 40% of the way to the squares' colour beyond what the
# code's own squares, blurred, put there; a line, at 5% of its tested points
QZ_OWN = 0.75 # within this many squares, only points beside background-coloured squares
QZ_MASK = 0.3 # points the code's own squares, blurred, shade this far toward their
# colour are not tested
QZ_POINTS = 6 # a line with fewer points to test is not tested: neither clear nor not
QZ_PAD = 5 # squares of background round the model of the code's own squares
QZ_EDGE_PPM, QZ_EDGE_NEAR = 4.0, 3.5 # under 4 pixels per square, where the grid places the code's edge only to
# within about a pixel, a margin the picture's edge ends from 3.5 squares out
# reads 4 ("capped"): on plain files at 2.25-3.5 px it read 3.5 or 3.75 for
# 4. A real 3.5 then reads 4 too, so the page states a margin only from
# margin_min_ppm (web/data/sizes.json), which must stay at or above this
def to_image(h, u, v):
w = h[2, 0] * u + h[2, 1] * v + h[2, 2]
return (h[0, 0] * u + h[0, 1] * v + h[0, 2]) / w, (h[1, 0] * u + h[1, 1] * v + h[1, 2]) / w
def sample(img, x, y):
"""Bilinear samples at image points; NaN off the picture, whose outer half pixel counts as on it (the border
pixels' own values there)."""
shape = np.shape(x)
xf, yf = np.ravel(x).astype(np.float32), np.ravel(y).astype(np.float32)
inside = np.isfinite(xf) & np.isfinite(yf) & (xf >= -0.5) & (yf >= -0.5) & (xf <= img.shape[1] - 0.5) & \
(yf <= img.shape[0] - 0.5)
cols = 1024
rows = max(1, -(-len(xf) // cols))
mx, my = np.full(rows * cols, -1, np.float32), np.full(rows * cols, -1, np.float32)
mx[:len(xf)], my[:len(xf)] = np.where(inside, xf, -1), np.where(inside, yf, -1)
v = cv2.remap(img, mx.reshape(rows, cols), my.reshape(rows, cols), cv2.INTER_LINEAR,
borderMode=cv2.BORDER_REPLICATE).ravel()[:len(xf)].astype(np.float64)
v[~inside] = np.nan
return v.reshape(shape)
def _phi(z):
"""Standard normal CDF (Abramowitz and Stegun 7.1.26, error under 1e-7): numpy has no erf."""
x = np.abs(z) / math.sqrt(2)
t = 1 / (1 + 0.3275911 * x)
erf = 1 - t * (0.254829592 + t * (-0.284496736 + t * (1.421413741 + t * (-1.453152027 + t * 1.061405429)))) \
* np.exp(-x * x)
return 0.5 * (1 + np.sign(z) * erf)
# ---- finder patterns -------------------------------------------------------------------------------------------
def _fit_grid(u, y, s, d, edges=EDGES):
"""Least squares of a finder's profile, blurred by each candidate s[i] with its edges at edges[i] (squares; the
same for all by default) and offset by each d: the light level, the step to the dark level, each half of the
square of margin outside the finder (light, unless something is printed there), and whatever lies beyond the
window on either side. Returns the best (i, j), the parabola's vertex t between grid points of i (0 at the ends),
and the fit's coefficients and squared error there."""
e = np.broadcast_to(edges, (len(s), len(EDGES)))
p = _phi((u[None, None, :, None] - d[None, :, None, None] - e[:, None, None, :]) / s[:, None, None, None])
dark = p[..., 2] - p[..., 3] + p[..., 4] - p[..., 5] + p[..., 6] - p[..., 7]
x = np.stack([np.ones_like(dark), dark, p[..., 0] - p[..., 1], p[..., 1] - p[..., 2], 1 - p[..., 0], p[..., 8]], -1)
xt = np.swapaxes(x, -1, -2)
xty = xt @ y
beta = np.linalg.solve(xt @ x + 1e-9 * np.eye(6), xty[..., None])[..., 0]
sse = float(y @ y) - (beta * xty).sum(-1)
i, j = np.unravel_index(np.argmin(sse), sse.shape)
if 0 < i < len(s) - 1: # between grid points: the vertex of a parabola through the three
a, b, c = sse[i - 1:i + 2, j]
curve = a - 2 * b + c
return i, j, 0.5 * (a - c) / curve if curve > 0 else 0.0, beta[i, j], max(float(b), 0.0)
return i, j, 0.0, beta[i, j], max(float(sse[i, j]), 0.0)
def fit_profile(y, u=U) -> dict:
"""Blur (squares), light and dark level of one profile across a finder (samples y at u), and whether the fit is
good enough; the profile itself is kept for the pattern's width (finder_width)."""
s, d = S_GRID, D_GRID
for _ in range(2): # the grid, then finer round the best: the blur's vertex in log(s)
i, j, t, beta, sse = _fit_grid(u, y, s, d)
best = s[i] * (s[i + 1] / s[i]) ** t if 0 < i < len(s) - 1 else s[i]
s, d, last = best * 1.25 ** np.linspace(-1, 1, 9), d[j] + np.linspace(-0.1, 0.1, 11), d[j]
s, d = best, last
step = float(beta[1])
rms = math.sqrt(sse / len(y))
ok = abs(step) >= MIN_STEP and rms <= FIT_RMS * abs(step) and s <= S_MAX and abs(d) <= 0.45
return {"s": float(s), "d": float(d), "light": float(beta[0]), "dark": float(beta[0]) + step, "ok": bool(ok),
"u": u, "y": y}
def finder_width(fit: dict) -> float:
"""How many times wider a finder pattern is than its profile's grid has it (its blur as fitted): the pattern's
edges at 3.5 + d + k (edge - 3.5) squares, k from 0.92 to 1.08 in steps of 0.02, then of 0.005 round the best,
between grid points at the vertex of a parabola (the offset d searched round the fitted one)."""
u, y, s = fit["u"], fit["y"], np.array([fit["s"]])
k, d = 1 + np.arange(-4, 5) * 0.02, fit["d"] + np.arange(-1, 2) * 0.02
for _ in range(2):
i, j, t, _, _ = _fit_grid(u, y, np.repeat(s, len(k)), d, 3.5 + (EDGES - 3.5) * k[:, None])
best = k[i] + t * (k[1] - k[0])
k, d = best + np.arange(-4, 5) * 0.005, d[j] + np.arange(-2, 3) * 0.005
return float(best)
def finder_fits(img, h, n: int, ppm: float) -> list[tuple[int, int, dict]]:
"""(finder, axis, fit) for each finder's profile along both axes, averaged over its central row of squares and
turned so that the code's margin comes first."""
lines = int(min(15, max(3, round(ppm))))
along, across = np.meshgrid(U, 3 + (np.arange(lines) + 0.5) / lines)
out = []
for f, (x0, y0) in enumerate(((0, 0), (n - 7, 0), (0, n - 7))):
for axis in (0, 1):
u, v = (x0 + along, y0 + across) if axis == 0 else (x0 + across, y0 + along)
prof = sample(img, *to_image(h, u, v)).mean(0)
if (f, axis) in ((1, 0), (2, 1)): # the margin lies beyond the far end: the pattern is symmetric
prof = prof[::-1]
seen = np.isfinite(prof)
k = int(np.argmax(seen))
if seen.any() and seen[k:].all() and k <= 15: # at most the margin square (and the outer ring's
# first half) lies off the picture
out.append((f, axis, fit_profile(prof[k:], U[k:])))
return out
# ---- the code's squares ----------------------------------------------------------------------------------------
def nanmean(a, axis):
"""Mean of the finite values along axis; NaN where there are none (without numpy's warning)."""
ok = np.isfinite(a)
count = ok.sum(axis)
return np.where(count > 0, np.where(ok, a, 0).sum(axis) / np.maximum(count, 1), np.nan)
def module_values(img, h, n: int):
"""Samples at the centre of every square: (row, column, 3, 3), within a fifth of a square of its centre."""
c = np.arange(n) + 0.5
off = np.array([-0.2, 0.0, 0.2])
u = c[None, :, None, None] + off[None, None, None, :]
v = c[:, None, None, None] + off[None, None, :, None]
u, v = np.broadcast_arrays(u, v)
return sample(img, *to_image(h, u, v))
def _otsu(v):
v = np.sort(v)
k = np.arange(1, len(v))
c = np.cumsum(v)[:-1]
w = k / len(v)
between = w * (1 - w) * (c / k - (v.sum() - c) / (len(v) - k)) ** 2
i = int(np.argmax(between))
return float(np.median(v[i + 1:])), float(np.median(v[:i + 1])), float(between[i] / max(v.var(), 1e-9))
def regions(m, n: int):
"""Light and dark level of each of g x g regions of the squares m (n x n), NaN where they don't split into two
levels (a logo, a blank, or contrast lost); and the regions' edges in squares."""
g = min(6, max(3, n // 5))
cut = np.round(np.linspace(0, n, g + 1)).astype(int)
out = np.full((g, g, 2), np.nan)
for i in range(g):
for j in range(g):
v = m[cut[i]:cut[i + 1], cut[j]:cut[j + 1]].ravel()
v = v[np.isfinite(v)]
if len(v) >= 18:
light, dark, eta = _otsu(v)
if eta >= 0.8 and light - dark >= 6:
out[i, j] = light, dark
return out, cut
# ---- the quiet zone ----------------------------------------------------------------------------------------------
def _edge_levels(m, k: int):
"""Per square along side k of the code (top, right, bottom, left as drawn): the lightest and darkest of the
nearest squares in the two outer rows, three squares wide, following the light across the code."""
strip = [m[:2, :], m[:, -2:].T, m[-2:, :], m[:, :2].T][k]
pad = np.pad(strip, ((0, 0), (1, 1)), constant_values=np.nan)
win = np.stack([pad[:, i:i + strip.shape[1]] for i in range(3)]).reshape(6, -1)
ok = np.isfinite(win)
light = np.where(ok, win, -np.inf).max(0)
dark = np.where(ok, win, np.inf).min(0)
return np.where(ok.any(0), light, np.nan), np.where(ok.any(0), dark, np.nan)
def _own_model(m, inverted: bool, blur: float):
"""What the code's own squares alone put round it: 1 where a square is the squares' colour (judged against the
lightest and darkest squares within two of it; unknown squares count as that colour), blurred by blur squares,
QZ_PAD squares of background round it, k samples a square. Returns the picture and k."""
seen = np.isfinite(m)
lo = cv2.erode(np.where(seen, m, np.inf).astype(np.float32), np.ones((5, 5), np.uint8))
hi = cv2.dilate(np.where(seen, m, -np.inf).astype(np.float32), np.ones((5, 5), np.uint8))
colour = (hi - m < m - lo) if inverted else (hi - m >= m - lo)
n = m.shape[0]
k = max(4, min(8, 1200 // (n + 2 * QZ_PAD)))
own = np.zeros(((n + 2 * QZ_PAD) * k,) * 2, np.float32)
own[QZ_PAD * k:(QZ_PAD + n) * k, QZ_PAD * k:(QZ_PAD + n) * k] = np.kron(np.where(seen, colour, True),
np.ones((k, k))).astype(np.float32)
return cv2.GaussianBlur(own, (0, 0), max(blur, 0.02) * k), k
def quiet_margins(img, h, n: int, m, levels, inverted: bool, blur: float, px: float):
"""Clear margin in squares per side of the code (as drawn), whether the picture's edge ended it, whether it is
only known to be under that (the lines nearer the code could not be tested), and whether it is capped (below).
m holds the squares' values; levels, light and dark per region of the code (k x 2), at least one; blur, the blur
in squares; px, the code's pixels per square in the frame.
A point intrudes when it lies QZ_TOWARD of the way from the background's level to the squares' colour beyond
what the code's own squares, blurred, put there; measured against the nearest squares at the code's edge, or
against whichever region of the code is most lenient, so shadow or glare over the code and its margin is not
taken for something printed. Points the code's own squares shade more than QZ_MASK are not tested, nor, on lines
within QZ_OWN squares, points beside a square of the squares' colour (so corners a little inside the code don't
make its own dark squares look like intrusions). A line with fewer than QZ_POINTS points to test is skipped: it
counts as neither clear nor intruded. Two rules for the code's own edge: a line within QZ_OWN squares that
intrudes, with no clear line between it and the code, ends the margin only when the next line out, a quarter
square further, isn't clear, since a mark at the code that doesn't reach it is the code's edge (a design's art
crossing it, or the edge's pixels at a few pixels a square), while a mark beyond a clear line, however thin, ends
the margin; and under QZ_EDGE_PPM pixels per square, a margin the picture's edge ends at QZ_EDGE_NEAR squares or
more reads 4, not ended by the edge, and capped."""
sign = 1.0 if inverted else -1.0 # the squares' colour lies this way from the background
bg_all, fg_all = (levels[:, 1], levels[:, 0]) if inverted else (levels[:, 0], levels[:, 1])
model, k_own = _own_model(m, inverted, blur)
out = []
for k in range(4):
light, dark = _edge_levels(m, k)
bg, fg = (dark, light) if inverted else (light, dark)
row = [m[0, :], m[:, -1], m[-1, :], m[:, 0]][k]
own = ~(np.abs(row - bg) < np.abs(row - fg)) # the outer square is the squares' colour (or unknown)
def line(d: float, k=k, bg=bg, fg=fg, own=own) -> str: # this side's, bound as defaults
"""The line d squares out: "off" the picture, "skip" (too few points to test), "mark" or "clear"."""
t = np.linspace(-d, n + d, int((n + 2 * d) * 6) + 1)
a, b = np.broadcast_arrays(t[None, :], d + np.array([-0.06, 0.0, 0.06])[:, None])
u, v = [(a, -b), (n + b, a), (a, n + b), (-b, a)][k]
s = sample(img, *to_image(h, u, v))
count = np.isfinite(s).sum(0)
seen = count > 0
if 1 - seen.mean() > 0.1: # the line runs off the picture
return "off"
total = np.where(np.isfinite(s), s, 0).sum(0) # the three lines' mean, smoothed over half a square
norm = np.maximum(np.convolve(count, np.ones(3), "same"), 1)
smooth = np.convolve(total, np.ones(3), "same") / norm
f = sample(model, (u + QZ_PAD) * k_own - 0.5, (v + QZ_PAD) * k_own - 0.5)
f = np.convolve(np.where(np.isfinite(s), f, 0).sum(0), np.ones(3), "same") / norm
j = np.clip(np.floor(t), 0, n - 1).astype(int)
tau = np.fmax(sign * bg[j] + (QZ_TOWARD + f) * np.abs(fg[j] - bg[j]),
np.max(sign * bg_all[:, None] + (QZ_TOWARD + f) * np.abs(fg_all - bg_all)[:, None], 0))
test = seen & (f <= QZ_MASK) & (~own[j] if d < QZ_OWN else True)
if test.sum() < QZ_POINTS:
return "skip"
return "mark" if (sign * smooth > tau)[test].mean() >= QZ_SHARE else "clear"
margin, edge, under, capped, clear, tested = 4.0, False, False, False, 0.0, False
ahead: dict[int, str] = {} # a line already looked at as the next one out
for i, d in enumerate(QZ_STEPS):
kind = ahead.pop(i, None) or line(d)
if kind == "off":
margin, edge = d - 0.125, True
if px < QZ_EDGE_PPM and margin >= QZ_EDGE_NEAR:
margin, edge, capped = 4.0, False, True
break
if kind == "skip":
continue
if kind == "mark" and d < QZ_OWN and i + 1 < len(QZ_STEPS) and not tested: # at the code's edge
ahead[i + 1] = line(QZ_STEPS[i + 1])
if ahead[i + 1] == "clear":
kind = "clear"
if kind == "mark":
margin, under = (clear, False) if tested or d == QZ_STEPS[0] else (d + 0.125, True)
break
clear, tested = d + 0.125, True
out.append((float(margin), edge, under, capped))
return out