import cv2 import numpy as np # preprocess.py # 推理前后处理:字形图归一化到画布、full6 的 3 通道输入、full6 输出的段拼成笔迹、own1 的 4 通道输入。 # 坐标约定:画布坐标 (x, y) ∈ [-1,1],对应 R×R 图的像素 ((x+1)/2·R, (y+1)/2·R)。 K, S, R = 16, 40, 256 SPAN = 0.8 # 字形最长边在 [-1,1] 画布里占 [-SPAN, SPAN] PAUSE, DUR0, SPEED = 0.18, 0.25, 0.9 # 时间轴:每条笔迹用时 0.25 + 长度 × 0.9(画布单位),笔迹之间停 0.18 def resample(poly, n): """按弧长把折线重采样成 n 个点(保留方向)。""" d = np.linalg.norm(np.diff(poly, axis=0), axis=1) s = np.concatenate([[0], np.cumsum(d)]) if s[-1] < 1e-6: return np.repeat(poly[:1], n, 0) t = np.linspace(0, s[-1], n) return np.stack([np.interp(t, s, poly[:, 0]), np.interp(t, s, poly[:, 1])], 1).astype(np.float32) def bbox_norm(lo, hi): """外框 → 画布坐标的变换(等比,居中):u = (p - c) * k。""" c = (lo + hi) / 2 k = 2 * SPAN / max(float((hi - lo).max()), 1e-3) return c, k def canon(img): """任意字形图(0..1,墨为 1)→ 按墨的外框归一化到 R×R 画布,返回图和 像素→画布坐标 的仿射 (a, b):u = a * px + b。""" ys, xs = np.nonzero(img > 0.5) if len(xs) == 0: return None lo = np.array([xs.min(), ys.min()], np.float32); hi = np.array([xs.max() + 1, ys.max() + 1], np.float32) c, k = bbox_norm(lo, hi) a = k * R / 2 # 源像素 → 目标像素的缩放 M = np.array([[a, 0, R / 2 - a * c[0]], [0, a, R / 2 - a * c[1]]], np.float32) out = cv2.warpAffine(img, M, (R, R), flags=cv2.INTER_AREA if a < 1 else cv2.INTER_LINEAR) return out, (k, -k * c) def features(img): """字形图 → full6 的 3 通道输入:抗锯齿墨、墨内距离、墨外距离。""" ink = (img > 0.5).astype(np.uint8) din = cv2.distanceTransform(ink, cv2.DIST_L2, 3) dout = cv2.distanceTransform(1 - ink, cv2.DIST_L2, 3) return np.stack([img, np.clip(din / 12, 0, 1), np.clip(dout / 24, 0, 1)]).astype(np.float32) def join_segments(segs, cont): """full6 输出的 (段 [T,K,2], 连着 [T]) → 笔迹列表:连着的段首尾相接成一条笔迹,笔迹之间抬笔。""" pens = [] for g, c in zip(segs, cont): if c and pens: pens[-1] = np.concatenate([pens[-1], g[1:]]) else: pens.append(np.asarray(g, np.float64)) return pens def point_times(pens): """每条笔迹每个点被写到的时刻(整字写完 = 1)。返回 (每条笔迹的时刻数组列表, 总时长)。""" tl, t = [], 0.0 for p in pens: L = float(np.linalg.norm(np.diff(p, axis=0), axis=1).sum()); d = DUR0 + L * SPEED tl.append((t, d, L)); t += d + PAUSE total = t - PAUSE; res = [] for p, (t0, d, L) in zip(pens, tl): s = np.r_[0, np.cumsum(np.linalg.norm(np.diff(p, axis=0), axis=1))] res.append((t0 + d * s / max(L, 1e-6)) / total) return res, total def render_traj(pens, times, R=R, thick=3): """轨迹 → (时刻图, 有无图):后写的先画、先写的后画,交叉处留先写的时刻。""" tm = np.zeros((R, R), np.float32); pr = np.zeros((R, R), np.float32) for p, t in reversed(list(zip(pens, times))): q = ((p + 1) / 2 * R * 16).round().astype(np.int32) for j in range(len(q) - 1): v = float((t[j] + t[j + 1]) / 2) cv2.line(tm, tuple(q[j]), tuple(q[j + 1]), v, thick, cv2.LINE_8, 4) cv2.line(pr, tuple(q[j]), tuple(q[j + 1]), 1.0, thick, cv2.LINE_8, 4) return tm, pr def own_input(feat, pens): """own1 的 4 通道输入 [4,R,R]:墨、墨内距离、轨迹时刻图、轨迹有无。feat 是 features() 的输出。""" tm, pr = render_traj(pens, point_times(pens)[0]) return np.stack([feat[0], feat[1], tm, pr]).astype(np.float32)