feat(image-vectorize): v0.2 换 potrace 引擎,只做单色/灰度
用户裁定「只要单色/灰度就够」后重做:VTracer(彩色分层 wasm)换成 potrace (纯 JS,Inkscape 同款内核)。文字笔画完整、turdSize 去掉毛刺、灰度层数 2–5。 - 纯 JS ⇒ 不需要宿主放宽 CSP;插件 238KB → 116KB - 自带 potrace 移植(GPL-2.0,去 jimp 依赖,改吃 ImageData),License 随目录 - 灰度阈值自己按等像素量分位算(上游 steps:5 要 28s,这里几十 ms), 并处理「主背景峰要排除」「切点必须严格递增」两个坑 - 新增 tools/trace-cli.mjs:拿真实素材直接跑参数、出对比图 - harness 重写 32 项(含「无 wasm-unsafe-eval 的 CSP 下跑通」反向锁);真站 e2e 13 项
This commit is contained in:
1 parent
6f3a4676bb
commit
c4e4b15375
29 files changed
+5949
-2321
No files matched your search
@@ -1,102 +1,172 @@
|
||||
/* VTracer 引擎封装。
|
||||
/**
|
||||
* 描摹引擎:potrace(纯 JS,GPL-2.0)—— 单色 / 灰度分层。
|
||||
*
|
||||
* 为什么这么薄:vtracer-wasm 只有 `to_svg(pixels, w, h, config)` 一个入口,
|
||||
* 参数语义在实测中与官方 CLI 有明显偏差(见 CONFIG_LIMITS),所以把它全部收在这里,
|
||||
* 上层(ui / trace)只跟「业务参数」打交道。
|
||||
* 为什么换成 potrace(2026-11-05 用户裁定后的第二版):
|
||||
* 上一版用 VTracer(彩色分层 + 样条拟合),文字图上会**断笔画、起毛刺、浅色块碎层**,
|
||||
* 用户实测「看着变矢量但没法用」。potrace 是「二值轮廓追踪 + 曲线拟合」:
|
||||
* 对 hard edge(文字、logo、线稿)的保形性明显更好,且 turdSize 天生能吃掉小毛刺。
|
||||
* 代价是它只懂明暗(不懂颜色),所以只做**单色**与**灰度分层**——
|
||||
* 用户明确说了「单色/灰度就够」,不再做彩色。
|
||||
*
|
||||
* 实测得出的三条硬约束(2026-11-05,Chromium + 800×800 合成图扫描):
|
||||
* 1. colorPrecision 的语义与 vtracer CLI 相反:wasm 侧直接把它当「颜色相似度阈值」
|
||||
* (is_same_color_a),值越大越容易把不同颜色并成一团。≥6 时整张图会塌成一个色块,
|
||||
* =8 直接 wasm abort(unreachable)。故夹在 1–5。
|
||||
* 2. wasm abort 后实例不可再用,且 __wbg_init 见到已有实例会直接返回坏的,
|
||||
* 所以 panic 后必须 __reset_wasm() 再重建,否则整个插件从此报错。
|
||||
* 3. 像素必须是 RGBA 四通道(ImageData.data 原样),长度 w*h*4。
|
||||
* 纯 JS ⇒ 不需要 wasm,**不需要宿主放宽 CSP**(上一版为此加过 'wasm-unsafe-eval',
|
||||
* 下线时已收回;本版不要再动 CSP)。
|
||||
*
|
||||
* 灰度分层为什么自己算阈值:上游 Posterizer 的 `steps` 传数字时会走直方图多级阈值搜索,
|
||||
* `steps: 5` 实测 28 秒(指数级),完全不可用。改为自己用**等像素量分位**算好阈值数组
|
||||
* 直接传进去(O(pixels)),5 层也只要几十毫秒。
|
||||
*/
|
||||
'use strict'
|
||||
|
||||
import init, { to_svg, __reset_wasm } from './vendor/vtracer.js'
|
||||
import wasmB64 from './vendor/wasm-b64.js'
|
||||
import Potrace from './vendor/potrace/Potrace.js'
|
||||
import Posterizer from './vendor/potrace/Posterizer.js'
|
||||
|
||||
// colorPrecision 安全区间(见文件头第 1 条)
|
||||
export const COLOR_PRECISION_MIN = 1
|
||||
export const COLOR_PRECISION_MAX = 5
|
||||
export const MODES = ['gray', 'mono']
|
||||
export const LEVELS_MIN = 2
|
||||
export const LEVELS_MAX = 5
|
||||
|
||||
let wasmBytes = null
|
||||
let initPromise = null
|
||||
/** 描摹上限边(超过就降采样):potrace 是纯 JS 单线程,2000px 以上会明显卡主线程 */
|
||||
export const MAX_TRACE_SIDE = 2000
|
||||
|
||||
function decodeWasm() {
|
||||
if (wasmBytes) return wasmBytes
|
||||
// 182KB base64 → 137KB 字节;只在首次描摹时解码,避免拖慢插件加载
|
||||
const bin = atob(wasmB64)
|
||||
const out = new Uint8Array(bin.length)
|
||||
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
|
||||
wasmBytes = out
|
||||
return out
|
||||
export const DEFAULTS = {
|
||||
mode: 'gray', // 'gray' 灰度分层 / 'mono' 纯单色
|
||||
levels: 3, // 灰度层数(2–5,仅 gray)
|
||||
threshold: -1, // -1 = 自动(两种模式都支持)
|
||||
turdSize: 3, // 去小点:面积小于它的碎片直接丢(毛刺/噪点克星)
|
||||
alphaMax: 1, // 拐角平滑:0 全折线、1 默认、1.334 最圆
|
||||
invert: false, // 反相:描摹亮部(黑底白字场景)
|
||||
color: '#1a1a1a', // mono 的填充色
|
||||
outScale: 1, // 输出尺寸倍率(只放大尺寸,不重算曲线)
|
||||
}
|
||||
|
||||
function ensureEngine() {
|
||||
if (!initPromise) {
|
||||
initPromise = init({ module_or_path: decodeWasm() }).catch(function (error) {
|
||||
initPromise = null
|
||||
throw new Error('描摹引擎初始化失败:' + (error && error.message ? error.message : String(error)))
|
||||
})
|
||||
}
|
||||
return initPromise
|
||||
const clampInt = (v, min, max, dflt) => {
|
||||
const n = Math.round(Number(v))
|
||||
return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : dflt
|
||||
}
|
||||
|
||||
function clampInt(value, min, max, fallback) {
|
||||
const n = Math.round(Number(value))
|
||||
if (!Number.isFinite(n)) return fallback
|
||||
return Math.max(min, Math.min(max, n))
|
||||
}
|
||||
|
||||
/** 业务参数 → wasm config(字段名 camelCase,枚举小写,与结构体字段一一对应) */
|
||||
export function toEngineConfig(p) {
|
||||
/** 把 UI / 记忆里的松散参数收敛成引擎能吃的确定值 */
|
||||
export function normalizeParams(p) {
|
||||
const src = p || {}
|
||||
return {
|
||||
binary: Boolean(p.binary),
|
||||
mode: p.mode === 'polygon' ? 'polygon' : 'spline',
|
||||
hierarchical: p.hierarchical === 'cutout' ? 'cutout' : 'stacked',
|
||||
cornerThreshold: Math.max(0, Math.min(180, Number(p.cornerThreshold) || 60)),
|
||||
lengthThreshold: Math.max(0.1, Math.min(10, Number(p.lengthThreshold) || 3.5)),
|
||||
// maxIterations 是曲线拟合的迭代次数。上游 CLI 默认 10,但实测只要 ≥3 就会过拟合抗锯齿边缘:
|
||||
// 一个正圆被拉成水滴形、圆角矩形的角被吃掉。2 是实测最稳的值(圆保持圆、直角保持直)。
|
||||
maxIterations: clampInt(p.maxIterations, 1, 10, 2),
|
||||
spliceThreshold: 45,
|
||||
filterSpeckle: clampInt(p.filterSpeckle, 0, 128, 4),
|
||||
// 黑白模式没有颜色聚类,这两个字段只是结构体必填,给安全值即可
|
||||
colorPrecision: clampInt(p.colorPrecision, COLOR_PRECISION_MIN, COLOR_PRECISION_MAX, 2),
|
||||
layerDifference: clampInt(p.layerDifference, 0, 64, 16),
|
||||
pathPrecision: 8,
|
||||
mode: src.mode === 'mono' ? 'mono' : 'gray',
|
||||
levels: clampInt(src.levels, LEVELS_MIN, LEVELS_MAX, DEFAULTS.levels),
|
||||
threshold: Number(src.threshold) >= 0 ? clampInt(src.threshold, 0, 255, 128) : -1,
|
||||
turdSize: clampInt(src.turdSize, 0, 64, DEFAULTS.turdSize),
|
||||
alphaMax: (() => {
|
||||
const n = Number(src.alphaMax)
|
||||
return Number.isFinite(n) ? Math.min(1.334, Math.max(0, n)) : DEFAULTS.alphaMax
|
||||
})(),
|
||||
invert: Boolean(src.invert),
|
||||
color: /^#[0-9a-f]{6}$/i.test(String(src.color || '')) ? String(src.color) : DEFAULTS.color,
|
||||
outScale: Math.min(4, Math.max(1, Number(src.outScale) || 1)),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 描摹一次。
|
||||
* @param {Uint8ClampedArray|Uint8Array} rgba 长度必须等于 w*h*4
|
||||
* @returns {Promise<{svg: string, ms: number}>}
|
||||
* 等像素量分位阈值:把亮度直方图按像素数切成 levels 段,返回 levels-1 个切点。
|
||||
*
|
||||
* 两个必须处理的坑(实测,不是理论问题):
|
||||
* 1. **主背景色要排除在人口统计之外**。电商图/菜单图里底色常占 60–80% 像素,
|
||||
* 不排除的话三个切点里有两个会落在背景里,文字还是跟背景分不开(等于没分层)。
|
||||
* 2. **切点必须严格递增**。背景是一个巨大的尖峰,多个切点会算出同一个亮度值,
|
||||
* 去重后层数变少(Posterizer 还会算出 0 透明度,整层消失)。
|
||||
*/
|
||||
export async function tracePixels(rgba, width, height, params) {
|
||||
const w = Math.round(width)
|
||||
const h = Math.round(height)
|
||||
if (!(w > 0) || !(h > 0)) throw new Error('图片尺寸无效')
|
||||
if (!rgba || rgba.length !== w * h * 4) throw new Error('像素数据长度与尺寸不符')
|
||||
|
||||
await ensureEngine()
|
||||
const config = toEngineConfig(params)
|
||||
const pixels = rgba instanceof Uint8Array ? rgba : new Uint8Array(rgba.buffer, rgba.byteOffset, rgba.length)
|
||||
const started = (typeof performance !== 'undefined' ? performance.now() : Date.now())
|
||||
|
||||
try {
|
||||
const svg = to_svg(pixels, w, h, config)
|
||||
const ms = Math.round((typeof performance !== 'undefined' ? performance.now() : Date.now()) - started)
|
||||
return { svg, ms }
|
||||
} catch (error) {
|
||||
// wasm abort 后实例已损坏,必须复位,否则下一次调用还是同一个坏实例
|
||||
initPromise = null
|
||||
try { __reset_wasm() } catch (e) { /* 复位本身失败也只能继续抛原始错误 */ }
|
||||
throw new Error(
|
||||
'描摹失败(引擎内部异常):' + (error && error.message ? error.message : String(error)) +
|
||||
'。请调大「颜色精度」的容错或换「黑白」模式重试'
|
||||
)
|
||||
function quantileThresholds(imageData, levels) {
|
||||
const hist = new Uint32Array(256)
|
||||
const data = imageData.data
|
||||
let total = 0
|
||||
for (let i = 0; i < data.length; i += 4) {
|
||||
const a = data[i + 3] / 255
|
||||
// 与 potrace 内部一致:透明按白底合成后再算亮度
|
||||
const r = 255 + (data[i] - 255) * a
|
||||
const g = 255 + (data[i + 1] - 255) * a
|
||||
const b = 255 + (data[i + 2] - 255) * a
|
||||
hist[Math.round(0.299 * r + 0.587 * g + 0.114 * b)]++
|
||||
total++
|
||||
}
|
||||
if (!total) return []
|
||||
|
||||
// 1) 排除主背景峰(最常见的那个亮度)
|
||||
let bg = 0
|
||||
let bgCount = 0
|
||||
for (let v = 0; v < 256; v++) if (hist[v] > bgCount) { bgCount = hist[v]; bg = v }
|
||||
const counted = total - bgCount
|
||||
// 内容太少(几乎纯色图)就退化成等间距,别硬分层
|
||||
if (counted < total * 0.02) {
|
||||
const out = []
|
||||
for (let k = 1; k < levels; k++) out.push(Math.round((255 * k) / levels))
|
||||
return out
|
||||
}
|
||||
|
||||
// 2) 在「非背景」像素上取等量分位(背景 bin 当 0 处理,但仍参与 value 轴)
|
||||
const saved = hist[bg]
|
||||
hist[bg] = 0
|
||||
const cuts = []
|
||||
const per = counted / levels
|
||||
let acc = 0
|
||||
let next = per
|
||||
for (let v = 0; v < 256 && cuts.length < levels - 1; v++) {
|
||||
acc += hist[v]
|
||||
while (acc >= next && cuts.length < levels - 1) {
|
||||
cuts.push(v)
|
||||
next += per
|
||||
}
|
||||
}
|
||||
hist[bg] = saved
|
||||
|
||||
// 3) 强制严格递增 + 留出余量(相邻层差至少 1 个亮度级)
|
||||
const out = []
|
||||
for (const c of cuts) {
|
||||
let v = c
|
||||
if (out.length && v <= out[out.length - 1]) v = out[out.length - 1] + 1
|
||||
if (v > 254) break
|
||||
out.push(v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* 描摹主入口(同步)。
|
||||
* @param {{width:number,height:number,data:Uint8ClampedArray}} imageData
|
||||
* @param {object} params
|
||||
* @returns {{svg:string, ms:number, paths:number, levels:number}}
|
||||
*/
|
||||
export function traceImageData(imageData, params) {
|
||||
const p = normalizeParams(params)
|
||||
const now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now())
|
||||
const t0 = now()
|
||||
let svg = ''
|
||||
let levels = 1
|
||||
|
||||
if (p.mode === 'mono') {
|
||||
const potrace = new Potrace({
|
||||
threshold: p.threshold >= 0 ? p.threshold : Potrace.THRESHOLD_AUTO,
|
||||
turdSize: p.turdSize,
|
||||
alphaMax: p.alphaMax,
|
||||
optCurve: true,
|
||||
optTolerance: 0.2,
|
||||
blackOnWhite: !p.invert,
|
||||
color: p.color,
|
||||
})
|
||||
potrace.loadImageData(imageData)
|
||||
svg = potrace.getSVG()
|
||||
} else {
|
||||
const cuts = quantileThresholds(imageData, p.levels)
|
||||
levels = cuts.length + 1
|
||||
const posterizer = new Posterizer({
|
||||
// 传数组 ⇒ 跳过上游的直方图多级阈值搜索(那玩意 5 层要 28s)
|
||||
steps: cuts.length ? cuts : [128],
|
||||
threshold: p.threshold >= 0 ? p.threshold : Potrace.THRESHOLD_AUTO,
|
||||
turdSize: p.turdSize,
|
||||
alphaMax: p.alphaMax,
|
||||
optCurve: true,
|
||||
optTolerance: 0.2,
|
||||
blackOnWhite: !p.invert,
|
||||
fillStrategy: 'median', // 灰度:每层取该层亮度中位数
|
||||
color: '#000000', // 灰度靠 fill-opacity 叠出来,底色固定黑
|
||||
})
|
||||
posterizer.loadImageData(imageData)
|
||||
svg = posterizer.getSVG()
|
||||
}
|
||||
|
||||
return { svg, ms: Math.round(now() - t0), paths: (String(svg).match(/<path/g) || []).length, levels }
|
||||
}
|
||||
Reference in new issue
Block a user