Files
iwb-plugins-desktop/image-vectorize/plugin/engine.js
T
qiqi c4e4b15375 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 项
2026-11-05 07:57:18 +08:00

173 lines
6.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 描摹引擎:potrace(纯 JS,GPL-2.0)—— 单色 / 灰度分层。
*
* 为什么换成 potrace(2026-11-05 用户裁定后的第二版):
* 上一版用 VTracer(彩色分层 + 样条拟合),文字图上会**断笔画、起毛刺、浅色块碎层**,
* 用户实测「看着变矢量但没法用」。potrace 是「二值轮廓追踪 + 曲线拟合」:
* 对 hard edge(文字、logo、线稿)的保形性明显更好,且 turdSize 天生能吃掉小毛刺。
* 代价是它只懂明暗(不懂颜色),所以只做**单色**与**灰度分层**——
* 用户明确说了「单色/灰度就够」,不再做彩色。
*
* 纯 JS ⇒ 不需要 wasm,**不需要宿主放宽 CSP**(上一版为此加过 'wasm-unsafe-eval',
* 下线时已收回;本版不要再动 CSP)。
*
* 灰度分层为什么自己算阈值:上游 Posterizer 的 `steps` 传数字时会走直方图多级阈值搜索,
* `steps: 5` 实测 28 秒(指数级),完全不可用。改为自己用**等像素量分位**算好阈值数组
* 直接传进去(O(pixels)),5 层也只要几十毫秒。
*/
'use strict'
import Potrace from './vendor/potrace/Potrace.js'
import Posterizer from './vendor/potrace/Posterizer.js'
export const MODES = ['gray', 'mono']
export const LEVELS_MIN = 2
export const LEVELS_MAX = 5
/** 描摹上限边(超过就降采样):potrace 是纯 JS 单线程,2000px 以上会明显卡主线程 */
export const MAX_TRACE_SIDE = 2000
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, // 输出尺寸倍率(只放大尺寸,不重算曲线)
}
const clampInt = (v, min, max, dflt) => {
const n = Math.round(Number(v))
return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : dflt
}
/** 把 UI / 记忆里的松散参数收敛成引擎能吃的确定值 */
export function normalizeParams(p) {
const src = p || {}
return {
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)),
}
}
/**
* 等像素量分位阈值:把亮度直方图按像素数切成 levels 段,返回 levels-1 个切点。
*
* 两个必须处理的坑(实测,不是理论问题):
* 1. **主背景色要排除在人口统计之外**。电商图/菜单图里底色常占 60–80% 像素,
* 不排除的话三个切点里有两个会落在背景里,文字还是跟背景分不开(等于没分层)。
* 2. **切点必须严格递增**。背景是一个巨大的尖峰,多个切点会算出同一个亮度值,
* 去重后层数变少(Posterizer 还会算出 0 透明度,整层消失)。
*/
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 }
}