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
+41
-222
@@ -1,250 +1,72 @@
|
||||
/* 位图转矢量的业务层:预设、预处理、SVG 规范化、回栅格。
|
||||
/* 描摹前处理与 SVG 输出工具(与引擎无关的纯工具函数)。
|
||||
*
|
||||
* 预处理为什么必要(实测 2026-11-05):单纯调 lengthThreshold / cornerThreshold 抹不掉
|
||||
* rembg 那种 ±3px 的毛边 —— 引擎会忠实保留每一个像素级抖动。先把图降采样到 1/2~1/4
|
||||
* (双线性插值天然把毛刺平均掉)再描摹,轮廓才真正变光滑,且耗时同步下降。
|
||||
* 代价是小字/细节会糊,所以做成可选强度,默认 1x 不做。
|
||||
* 上一版(VTracer)里的降噪、背景层剔除、viewBox 修补在这里**全部删掉**了:
|
||||
* - 降噪:potrace 的 turdSize 天生去小点,不需要先降采样糊一遍;
|
||||
* - 背景层剔除:potrace 按明暗分层,白底自然成为最亮的一层,不再需要删 path;
|
||||
* - viewBox 修补:potrace 自己就输出 width/height/viewBox(实测),不用二次拼接。
|
||||
* 留下的只有:读图 → 必要时降采样 → 生成 PNG / 统计。
|
||||
*/
|
||||
'use strict'
|
||||
|
||||
import { COLOR_PRECISION_MIN, COLOR_PRECISION_MAX } from './engine.js'
|
||||
import { MAX_TRACE_SIDE } from './engine.js'
|
||||
|
||||
/** 描摹侧边长上限:超过则自动降采样(4000px 原图直描会卡住主线程好几秒) */
|
||||
export const MAX_TRACE_SIDE = 2000
|
||||
|
||||
export const PRESETS = {
|
||||
logo: {
|
||||
label: '标志 / 图标',
|
||||
hint: '纯色块、边缘清晰',
|
||||
binary: false, hierarchical: 'stacked', mode: 'spline',
|
||||
colorPrecision: 2, layerDifference: 16, filterSpeckle: 4,
|
||||
cornerThreshold: 90, lengthThreshold: 3.5, maxIterations: 2, denoise: 1, bg: 'auto',
|
||||
},
|
||||
art: {
|
||||
label: '插画 / 卡通',
|
||||
hint: '色块多、有渐变',
|
||||
binary: false, hierarchical: 'stacked', mode: 'spline',
|
||||
colorPrecision: 3, layerDifference: 24, filterSpeckle: 4,
|
||||
cornerThreshold: 90, lengthThreshold: 4, maxIterations: 2, denoise: 1,
|
||||
},
|
||||
photo: {
|
||||
label: '照片',
|
||||
hint: '色层多、体积大',
|
||||
binary: false, hierarchical: 'stacked', mode: 'spline',
|
||||
colorPrecision: 4, layerDifference: 48, filterSpeckle: 2,
|
||||
cornerThreshold: 60, lengthThreshold: 4, maxIterations: 3, denoise: 2,
|
||||
},
|
||||
line: {
|
||||
label: '线稿 / 黑白',
|
||||
hint: '二值描摹,单色',
|
||||
binary: true, hierarchical: 'stacked', mode: 'spline',
|
||||
colorPrecision: 2, layerDifference: 16, filterSpeckle: 8,
|
||||
cornerThreshold: 90, lengthThreshold: 4, maxIterations: 2, denoise: 1,
|
||||
},
|
||||
edge: {
|
||||
label: '边缘净化',
|
||||
hint: '清理抠图毛边,轮廓变光滑',
|
||||
binary: false, hierarchical: 'stacked', mode: 'spline',
|
||||
colorPrecision: 2, layerDifference: 16, filterSpeckle: 16,
|
||||
cornerThreshold: 90, lengthThreshold: 6, maxIterations: 1, denoise: 3,
|
||||
},
|
||||
}
|
||||
|
||||
export const PARAM_META = {
|
||||
colorPrecision: { label: '颜色精度', min: COLOR_PRECISION_MIN, max: COLOR_PRECISION_MAX, step: 1, hint: '越大色块越少(引擎阈值为反语义,已夹在 1–5)' },
|
||||
layerDifference: { label: '色层差异', min: 0, max: 64, step: 2, hint: '越大越容易合并相邻色层' },
|
||||
filterSpeckle: { label: '噪点过滤', min: 0, max: 128, step: 1, hint: '丢弃小于该面积的碎块' },
|
||||
cornerThreshold: { label: '拐角阈值', min: 0, max: 180, step: 5, hint: '越大拐角越硬' },
|
||||
lengthThreshold: { label: '路径简化', min: 0.1, max: 10, step: 0.5, hint: '越大曲线越简、节点越少' },
|
||||
maxIterations: { label: '曲线迭代', min: 1, max: 10, step: 1, hint: '越大越贴合原图,但过拟合会把圆拉变形' },
|
||||
}
|
||||
|
||||
export function clampParams(raw) {
|
||||
const p = Object.assign({}, PRESETS.logo, raw || {})
|
||||
const num = (key, fallback) => {
|
||||
const meta = PARAM_META[key]
|
||||
const n = Number(p[key])
|
||||
if (!Number.isFinite(n)) return fallback
|
||||
return Math.max(meta.min, Math.min(meta.max, n))
|
||||
}
|
||||
return {
|
||||
binary: Boolean(p.binary),
|
||||
hierarchical: p.hierarchical === 'cutout' ? 'cutout' : 'stacked',
|
||||
mode: p.mode === 'polygon' ? 'polygon' : 'spline',
|
||||
colorPrecision: Math.round(num('colorPrecision', 2)),
|
||||
layerDifference: Math.round(num('layerDifference', 16)),
|
||||
filterSpeckle: Math.round(num('filterSpeckle', 4)),
|
||||
cornerThreshold: num('cornerThreshold', 60),
|
||||
lengthThreshold: num('lengthThreshold', 3.5),
|
||||
maxIterations: Math.round(num('maxIterations', 2)),
|
||||
denoise: Math.max(1, Math.min(4, Math.round(Number(p.denoise) || 1))),
|
||||
bg: p.bg === 'keep' ? 'keep' : 'auto',
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 采样画布四角颜色(用于判断「有没有统一背景」)。
|
||||
* @returns {[number,number,number]|null} 四角一致时返回该颜色,否则 null
|
||||
*/
|
||||
export function cornerColor(imageData, tolerance) {
|
||||
const w = imageData.width
|
||||
const h = imageData.height
|
||||
const px = imageData.data
|
||||
const tol = tolerance === undefined ? 20 : tolerance
|
||||
const at = function (x, y) {
|
||||
const i = (y * w + x) * 4
|
||||
return [px[i], px[i + 1], px[i + 2], px[i + 3]]
|
||||
}
|
||||
const list = [at(0, 0), at(w - 1, 0), at(0, h - 1), at(w - 1, h - 1)].filter(function (c) { return c[3] > 8 })
|
||||
if (list.length < 3) return null
|
||||
const base = list[0]
|
||||
for (const c of list) {
|
||||
if (Math.abs(c[0] - base[0]) > tol || Math.abs(c[1] - base[1]) > tol || Math.abs(c[2] - base[2]) > tol) return null
|
||||
}
|
||||
return [base[0], base[1], base[2]]
|
||||
}
|
||||
|
||||
function hexToRgb(hex) {
|
||||
const m = /^#([0-9a-f]{6})$/i.exec(hex)
|
||||
if (!m) return null
|
||||
const n = parseInt(m[1], 16)
|
||||
return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
|
||||
}
|
||||
|
||||
/** 估计一条 path 的实际包围盒:d 里的坐标对 + transform 的 translate 平移 */
|
||||
function pathExtent(d, tx, ty) {
|
||||
const nums = String(d).match(/-?\d+(?:\.\d+)?/g)
|
||||
if (!nums || nums.length < 4) return null
|
||||
let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity
|
||||
for (let i = 0; i + 1 < nums.length; i += 2) {
|
||||
const x = Number(nums[i]) + tx
|
||||
const y = Number(nums[i + 1]) + ty
|
||||
if (!Number.isFinite(x) || !Number.isFinite(y)) continue
|
||||
if (x < minX) minX = x
|
||||
if (x > maxX) maxX = x
|
||||
if (y < minY) minY = y
|
||||
if (y > maxY) maxY = y
|
||||
}
|
||||
if (!Number.isFinite(minX) || !Number.isFinite(minY)) return null
|
||||
return { minX, maxX, minY, maxY }
|
||||
}
|
||||
|
||||
/**
|
||||
* 从描摹结果里剔掉「铺满画布的背景层」。
|
||||
*
|
||||
* 为什么在 SVG 层面做,而不是描摹前把背景像素改成透明(实测走过的弯路):
|
||||
* 喂给引擎带 alpha 的图会触发它的 color keying,透明区被填成 key color 后
|
||||
* 与图中相近的颜色混淆 —— 实测红圆直接变形、中文笔画塌成黑块。
|
||||
* 保持描摹输入是原图,只在输出里删掉那一条背景 path,主体质量不受任何影响。
|
||||
*
|
||||
* @param {string} svg 引擎输出
|
||||
* @param {number} w 描摹宽
|
||||
* @param {number} h 描摹高
|
||||
* @param {[number,number,number]|null} bgRgb 四角背景色(null 则只按几何判断)
|
||||
* @returns {{svg: string, removed: boolean}}
|
||||
*/
|
||||
export function stripBackgroundLayer(svg, w, h, bgRgb) {
|
||||
const text = String(svg)
|
||||
const start = text.indexOf('<path')
|
||||
if (start < 0) return { svg: text, removed: false }
|
||||
const end = text.indexOf('/>', start)
|
||||
if (end < 0) return { svg: text, removed: false }
|
||||
const tag = text.slice(start, end + 2)
|
||||
|
||||
const fillMatch = /fill="(#[0-9A-Fa-f]{6})"/.exec(tag)
|
||||
const dMatch = /d="([^"]+)"/.exec(tag)
|
||||
if (!fillMatch || !dMatch) return { svg: text, removed: false }
|
||||
|
||||
if (bgRgb) {
|
||||
const rgb = hexToRgb(fillMatch[1])
|
||||
if (!rgb) return { svg: text, removed: false }
|
||||
// 背景层颜色必须与四角采样接近,否则说明第一条不是背景(透明底图/贴边主体)
|
||||
const diff = Math.max(Math.abs(rgb[0] - bgRgb[0]), Math.abs(rgb[1] - bgRgb[1]), Math.abs(rgb[2] - bgRgb[2]))
|
||||
if (diff > 24) return { svg: text, removed: false }
|
||||
}
|
||||
|
||||
const tr = /translate\(\s*(-?[\d.]+)\s*[, ]\s*(-?[\d.]+)\s*\)/.exec(tag)
|
||||
const ext = pathExtent(dMatch[1], tr ? Number(tr[1]) : 0, tr ? Number(tr[2]) : 0)
|
||||
if (!ext) return { svg: text, removed: false }
|
||||
|
||||
const coverW = (ext.maxX - ext.minX) / w
|
||||
const coverH = (ext.maxY - ext.minY) / h
|
||||
// 覆盖 ≥85% 画布才算背景;主体满幅的图(纯色块)删掉会变成空白,靠颜色比对已经挡了一层
|
||||
if (coverW < 0.85 || coverH < 0.85) return { svg: text, removed: false }
|
||||
|
||||
return { svg: text.slice(0, start) + text.slice(end + 2), removed: true }
|
||||
}
|
||||
|
||||
export function loadImage(src) {
|
||||
/** 读 data URL 成 <img>(走浏览器解码,与画布语义一致) */
|
||||
export function loadImage(dataUrl) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
const img = new Image()
|
||||
img.onload = function () { resolve(img) }
|
||||
img.onerror = function () { reject(new Error('图片解码失败')) }
|
||||
img.src = src
|
||||
img.src = dataUrl
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 预处理:按 denoise 倍数降采样(并把超大图夹到 MAX_TRACE_SIDE 内)。
|
||||
* @returns {{ canvas: HTMLCanvasElement, w: number, h: number, scale: number, clamped: boolean }}
|
||||
* 准备描摹用的像素:potrace 是单线程纯 JS,超过 MAX_TRACE_SIDE 会明显卡主线程,
|
||||
* 所以先按长边夹取(**只缩不放**)。
|
||||
* @returns {{canvas:HTMLCanvasElement, w:number, h:number, srcW:number, srcH:number, clamped:boolean}}
|
||||
*/
|
||||
export function prepareSource(img, denoise) {
|
||||
export function prepareSource(img) {
|
||||
const srcW = img.naturalWidth || img.width
|
||||
const srcH = img.naturalHeight || img.height
|
||||
if (!(srcW > 0) || !(srcH > 0)) throw new Error('图片尺寸无效')
|
||||
|
||||
let scale = 1 / Math.max(1, Math.min(4, Math.round(denoise) || 1))
|
||||
const clamped = Math.max(srcW, srcH) * scale > MAX_TRACE_SIDE
|
||||
if (clamped) scale = MAX_TRACE_SIDE / Math.max(srcW, srcH)
|
||||
|
||||
const w = Math.max(1, Math.round(srcW * scale))
|
||||
const h = Math.max(1, Math.round(srcH * scale))
|
||||
const longSide = Math.max(srcW, srcH)
|
||||
const k = longSide > MAX_TRACE_SIDE ? MAX_TRACE_SIDE / longSide : 1
|
||||
const w = Math.max(1, Math.round(srcW * k))
|
||||
const h = Math.max(1, Math.round(srcH * k))
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = w
|
||||
canvas.height = h
|
||||
const g = canvas.getContext('2d')
|
||||
g.imageSmoothingEnabled = true
|
||||
g.imageSmoothingQuality = 'high'
|
||||
g.drawImage(img, 0, 0, w, h)
|
||||
return { canvas, w, h, scale: w / srcW, clamped, srcW, srcH }
|
||||
const ctx = canvas.getContext('2d', { willReadFrequently: true })
|
||||
ctx.imageSmoothingEnabled = true
|
||||
ctx.drawImage(img, 0, 0, w, h)
|
||||
return { canvas, w, h, srcW, srcH, clamped: k < 1 }
|
||||
}
|
||||
|
||||
/**
|
||||
* vtracer 产出的 svg 只有 width/height 没有 viewBox(描摹尺寸即画布尺寸)。
|
||||
* 降采样后必须补 viewBox 才能放大回原始尺寸而不失真,否则浏览器按降采样尺寸渲染。
|
||||
*/
|
||||
export function withViewBox(svg, tracedW, tracedH, outW, outH) {
|
||||
return String(svg).replace(/<svg([^>]*)>/, function (_m, attrs) {
|
||||
const rest = attrs.replace(/\s(?:width|height|viewBox)="[^"]*"/g, '')
|
||||
return '<svg' + rest + ' width="' + Math.round(outW) + '" height="' + Math.round(outH) +
|
||||
'" viewBox="0 0 ' + tracedW + ' ' + tracedH + '" preserveAspectRatio="xMidYMid meet">'
|
||||
})
|
||||
}
|
||||
|
||||
/** SVG → 位图。走 blob: URL(宿主 img-src 放行 blob:,且不污染画布)。 */
|
||||
/** SVG 字符串 → <img>(导出时把矢量光栅化) */
|
||||
export function svgToImage(svg) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
const blob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const img = new Image()
|
||||
img.onload = function () { URL.revokeObjectURL(url); resolve(img) }
|
||||
img.onerror = function () { URL.revokeObjectURL(url); reject(new Error('矢量结果渲染失败')) }
|
||||
img.onerror = function () { URL.revokeObjectURL(url); reject(new Error('矢量渲染失败')) }
|
||||
img.src = url
|
||||
})
|
||||
}
|
||||
|
||||
/** SVG → 透明底 PNG Blob(outScale 倍超采样,边缘抗锯齿更好) */
|
||||
/**
|
||||
* 把矢量结果光栅化成 PNG(保存为节点用)。outScale 只影响像素尺寸 ——
|
||||
* 曲线按 viewBox 缩放渲染,所以 2× 是真的更清晰,不是插值放大。
|
||||
*/
|
||||
export async function svgToPngBlob(svg, baseW, baseH, outScale) {
|
||||
const img = await svgToImage(svg)
|
||||
const scale = Math.max(1, Math.min(4, Math.round(outScale) || 1))
|
||||
const w = Math.round(baseW * scale)
|
||||
const h = Math.round(baseH * scale)
|
||||
const k = Math.max(1, Math.min(4, Number(outScale) || 1))
|
||||
const w = Math.max(1, Math.round(baseW * k))
|
||||
const h = Math.max(1, Math.round(baseH * k))
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = w
|
||||
canvas.height = h
|
||||
const g = canvas.getContext('2d')
|
||||
g.clearRect(0, 0, w, h)
|
||||
g.drawImage(img, 0, 0, w, h)
|
||||
const ctx = canvas.getContext('2d')
|
||||
ctx.drawImage(img, 0, 0, w, h)
|
||||
return new Promise(function (resolve, reject) {
|
||||
canvas.toBlob(function (blob) {
|
||||
if (blob) resolve(blob)
|
||||
@@ -253,16 +75,13 @@ export async function svgToPngBlob(svg, baseW, baseH, outScale) {
|
||||
})
|
||||
}
|
||||
|
||||
/** 统计:路径数、文件体积、颜色数 —— 面板底部展示,让「参数调大了会怎样」可见 */
|
||||
/** 统计:路径数、填充色数、字节数(面板上「体积」那个数字) */
|
||||
export function svgStats(svg) {
|
||||
const s = String(svg)
|
||||
const paths = (s.match(/<path/g) || []).length
|
||||
const colors = new Set((s.match(/fill="#[0-9A-Fa-f]{6}"/g) || []).map(function (m) { return m.toLowerCase() }))
|
||||
return { paths, colors: colors.size, bytes: new Blob([s]).size }
|
||||
}
|
||||
|
||||
/** 「1x / 1/2 / 1/3 / 1/4」的展示文案 */
|
||||
export function denoiseLabel(v) {
|
||||
const n = Math.max(1, Math.min(4, Math.round(v) || 1))
|
||||
return n === 1 ? '原尺寸' : '1/' + n
|
||||
const text = String(svg)
|
||||
const paths = (text.match(/<path/g) || []).length
|
||||
const fills = []
|
||||
const re = /fill="([^"]+)"/g
|
||||
let m
|
||||
while ((m = re.exec(text))) if (fills.indexOf(m[1]) < 0) fills.push(m[1])
|
||||
return { paths: paths, colors: fills.length, bytes: text.length }
|
||||
}
|
||||
Reference in new issue
Block a user