import { text, num, choice, color, assert, parseJSON, numeric, points, source, pixels, canvas, png, json, luminance } from './common.js';
const sameSize = (images) => { assert(images.length === 2 && images[0].width === images[1].width && images[0].height === images[1].height, '需要两张同尺寸图片。'); };
const percent = (value) => { const n = numeric(value); assert(n >= 0 && n <= 100, '坐标百分比应为0–100。'); return n / 100; };
function linearSolve(rows) { const n = rows.length; for (let col = 0; col < n; col++) { let pivot = col; for (let i = col + 1; i < n; i++) if (Math.abs(rows[i][col]) > Math.abs(rows[pivot][col])) pivot = i; assert(Math.abs(rows[pivot][col]) > 1e-10, '四角退化,无法求解透视变换。'); [rows[col], rows[pivot]] = [rows[pivot], rows[col]]; const divisor = rows[col][col]; for (let j = col; j <= n; j++) rows[col][j] /= divisor; for (let i = 0; i < n; i++) if (i !== col) { const factor = rows[i][col]; for (let j = col; j <= n; j++) rows[i][j] -= factor * rows[col][j]; } } return rows.map((r) => r[n]); }
export const perspective_correct = (() => ({ fields: [text('corners', '四角百分比:左上、右上、右下、左下', '[[0,0],[100,0],[100,100],[0,100]]', true), num('width', '输出宽度', 256, 16, 1600), num('height', '输出高度', 192, 16, 1600)], async run({ images, values: v }) {
const input = source(images, 2e6), src = pixels(input), corners = points(v.corners, 4, 4).map((p) => p.map(percent)); assert(v.width * v.height <= 2e6, '透视输出最多2MP。'); const crosses = corners.map((b, i) => { const a = corners[(i + 3) % 4], c = corners[(i + 1) % 4]; return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]); }); assert(crosses.every((n) => n > 1e-6) || crosses.every((n) => n < -1e-6), '四角必须按边界顺序围成凸四边形。');
const dest = [[0,0],[1,0],[1,1],[0,1]], equations = []; dest.forEach(([u, w], i) => { const [x,y] = corners[i]; equations.push([u,w,1,0,0,0,-x*u,-x*w,x], [0,0,0,u,w,1,-y*u,-y*w,y]); }); const h = linearSolve(equations), out = new ImageData(v.width, v.height);
for (let y = 0; y < v.height; y++) { for (let x = 0; x < v.width; x++) { const u = x / (v.width - 1), w = y / (v.height - 1), d = h[6] * u + h[7] * w + 1, sx = Math.max(0, Math.min(src.width - 1, (h[0] * u + h[1] * w + h[2]) / d * (src.width - 1))), sy = Math.max(0, Math.min(src.height - 1, (h[3] * u + h[4] * w + h[5]) / d * (src.height - 1))), x0 = Math.floor(sx), y0 = Math.floor(sy), dx = sx - x0, dy = sy - y0, samples = [[x0,y0,(1-dx)*(1-dy)],[Math.min(x0+1,src.width-1),y0,dx*(1-dy)],[x0,Math.min(y0+1,src.height-1),(1-dx)*dy],[Math.min(x0+1,src.width-1),Math.min(y0+1,src.height-1),dx*dy]]; const index = (y * v.width + x) * 4, rgba = [0,0,0,0];
for (const [px,py,weight] of samples) { const i = (py * src.width + px) * 4, alpha = src.data[i+3] / 255; rgba[3] += alpha * weight; for (let c=0;c<3;c++) rgba[c] += src.data[i+c] * alpha * weight; } for (let c=0;c<3;c++) out.data[index+c] = rgba[3] ? rgba[c] / rgba[3] : 0; out.data[index+3] = rgba[3] * 255;
} if (y % 64 === 0) await new Promise((r) => setTimeout(r,0)); }
const node = canvas(v.width, v.height); node.getContext('2d').putImageData(out,0,0); return [await png(node,'rectified.png'), json({ corners, homographyDestinationToSource: [...h,1], output: [v.width,v.height], interpolation: '双线性,预乘Alpha取样' },'perspective.json')];
} }))();
export const image_annotate = (() => ({ fields: [text('annotations', '标注JSON(百分比坐标)', '[{"type":"rect","x":10,"y":10,"width":70,"height":65},{"type":"arrow","x":10,"y":85,"toX":75,"toY":25},{"type":"text","x":15,"y":40,"text":"重点"}]', true), color('stroke', '标注颜色', '#ffcc33'), num('lineWidth', '线宽(px)', 2, 1, 20), num('fontSize', '字号(px)', 12, 8, 120)], async run({ images, values: v }) {
const node = source(images), ctx = node.getContext('2d'), items = parseJSON(v.annotations); assert(Array.isArray(items) && items.length >= 1 && items.length <= 100, '需要1–100个标注。'); ctx.strokeStyle = v.stroke; ctx.fillStyle = v.stroke; ctx.lineWidth = v.lineWidth; ctx.font = `${v.fontSize}px sans-serif`;
for (const item of items) { const x = percent(item.x) * node.width, y = percent(item.y) * node.height;
if (item.type === 'rect') { const w = percent(item.width) * node.width, h = percent(item.height) * node.height; assert(w > 0 && h > 0 && x+w <= node.width+.001 && y+h <= node.height+.001, '矩形应在图片内。'); ctx.strokeRect(x,y,w,h); }
else if (item.type === 'arrow') { const tx=percent(item.toX)*node.width, ty=percent(item.toY)*node.height, length=Math.hypot(tx-x,ty-y); assert(length>1,'箭头长度过短。'); const a=Math.atan2(ty-y,tx-x), head=Math.min(length*.35,Math.max(6,v.lineWidth*4)); ctx.beginPath();ctx.moveTo(x,y);ctx.lineTo(tx,ty);ctx.moveTo(tx-head*Math.cos(a-.5),ty-head*Math.sin(a-.5));ctx.lineTo(tx,ty);ctx.lineTo(tx-head*Math.cos(a+.5),ty-head*Math.sin(a+.5));ctx.stroke(); }
else if (item.type === 'text') { assert(typeof item.text==='string' && [...item.text].length<=100 && item.text.trim(),'标注文字需为1–100字符。'); assert(x+ctx.measureText(item.text).width<=node.width && y>=v.fontSize && y+v.fontSize*.25<=node.height,'文字超出图片,请修改位置、字号或内容。');ctx.fillText(item.text,x,y); }
else throw new Error('标注type仅支持rect、arrow和text。');
}
return [await png(node,'annotated.png'),json({annotations:items,unit:'percent',fontSize:v.fontSize,lineWidth:v.lineWidth},'annotations.json')];
} }))();
export const image_magnifier = (() => ({ fields: [num('x','选区左边(%)',25,0,95),num('y','选区上边(%)',25,0,95),num('width','选区宽度(%)',25,1,100),num('height','选区高度(%)',25,1,100),num('zoom','放大倍数',3,1.5,8,.5),color('stroke','外框颜色','#e68a33')],async run({images,values:v}) {
const input=source(images);assert(v.x+v.width<=100&&v.y+v.height<=100,'选区超出图片。');const x=Math.floor(input.width*v.x/100),y=Math.floor(input.height*v.y/100),w=Math.max(1,Math.round(input.width*v.width/100)),h=Math.max(1,Math.round(input.height*v.height/100)),zw=Math.ceil(w*v.zoom),zh=Math.ceil(h*v.zoom),gap=40;
assert(input.width+zw+gap+40<=4096&&Math.max(input.height,zh)+40<=4096,'放大结果超过4096px。');const node=canvas(input.width+zw+gap+40,Math.max(input.height,zh)+40,'#ffffff'),ctx=node.getContext('2d'),mx=input.width+gap+20;ctx.drawImage(input,20,20);ctx.imageSmoothingEnabled=false;ctx.drawImage(input,x,y,w,h,mx,20,zw,zh);ctx.strokeStyle=v.stroke;ctx.lineWidth=2;ctx.strokeRect(20+x,20+y,w,h);ctx.strokeRect(mx,20,zw,zh);ctx.beginPath();ctx.moveTo(20+x+w,20+y);ctx.lineTo(mx,20);ctx.moveTo(20+x+w,20+y+h);ctx.lineTo(mx,20+zh);ctx.stroke();
return [await png(node,'magnified.png'),json({region:{x,y,width:w,height:h},magnified:{width:zw,height:zh},interpolation:'nearest-neighbor'},'magnifier.json')];
} }))();
export const image_ruler = (() => ({ fields: [num('pixelsPerUnit','每单位像素数',10,.1,10000,.1),text('unit','单位名称','mm'),num('step','大刻度间隔(单位)',1,.1,1000,.1)],async run({images,values:v}) {
const input=source(images),interval=v.pixelsPerUnit*v.step;assert(interval>=8&&Math.max(input.width,input.height)/interval<=300,'大刻度至少间隔8px,最多300段。');assert(v.unit.length<=12,'单位名称最多12字符。');const margin=48,node=canvas(input.width+margin,input.height+margin,'#ffffff'),ctx=node.getContext('2d');ctx.drawImage(input,margin,margin);ctx.strokeStyle='#167d68';ctx.fillStyle='#203d32';ctx.font='10px sans-serif';
for(let axis=0;axis<2;axis++){const length=axis?input.height:input.width;for(let i=0;i*interval<=length;i++){const p=margin+i*interval;ctx.beginPath();if(axis){ctx.moveTo(margin-8,p);ctx.lineTo(margin,p);}else{ctx.moveTo(p,margin-8);ctx.lineTo(p,margin);}ctx.stroke();const value=String(+(i*v.step).toFixed(4));if(axis)ctx.fillText(value,2,p+3);else{ctx.save();ctx.translate(p+3,margin-12);ctx.rotate(-Math.PI/2);ctx.fillText(value,0,0);ctx.restore();}}}ctx.fillText(v.unit,4,14);
return [await png(node,'ruler.png'),json({pixelsPerUnit:v.pixelsPerUnit,unit:v.unit,physicalWidth:input.width/v.pixelsPerUnit,physicalHeight:input.height/v.pixelsPerUnit,originPixel:[48,48],note:'刻度按用户输入校准,图片本身不能证明实际物理尺寸。'},'calibration.json')];
} }))();
export const image_anaglyph = (() => ({ fields:[choice('mode','合成方式',[['color','左红 + 右绿蓝'],['gray','亮度红青']])],async run({images,values:v}){
sameSize(images);const left=pixels(source(images)),right=pixels(source([images[1]])),out=new ImageData(left.width,left.height);
for(let i=0;i<out.data.length;i+=4){const la=left.data[i+3]/255,ra=right.data[i+3]/255,l=[left.data[i]*la,left.data[i+1]*la,left.data[i+2]*la],r=[right.data[i]*ra,right.data[i+1]*ra,right.data[i+2]*ra];out.data[i]=v.mode==='gray'?luminance(...l):l[0];out.data[i+1]=v.mode==='gray'?luminance(...r):r[1];out.data[i+2]=v.mode==='gray'?luminance(...r):r[2];out.data[i+3]=255;}
const node=canvas(left.width,left.height);node.getContext('2d').putImageData(out,0,0);return[await png(node,'anaglyph.png'),json({mode:v.mode,left:images[0].file.name,right:images[1].file.name,background:'black',note:'透明部分先合成黑色;需合适的左右视差图与红青眼镜。'},'anaglyph.json')];
} }))();
export const texture_seam = (() => ({ fields:[num('threshold','边缘通道差阈值',20,0,255)],async run({images,values:v}){
const input=source(images),p=pixels(input);assert(p.width>=2&&p.height>=2,'纹理至少2×2像素。');const node=canvas(input.width*2,input.height*2),ctx=node.getContext('2d');for(let y=0;y<2;y++)for(let x=0;x<2;x++)ctx.drawImage(input,x*input.width,y*input.height);
function compare(horizontal){const length=horizontal?p.height:p.width;let sum=0,max=0,above=0;for(let i=0;i<length;i++){const a=horizontal?i*p.width*4:i*4,b=horizontal?(i*p.width+p.width-1)*4:((p.height-1)*p.width+i)*4;let pixelMax=0;for(let c=0;c<4;c++){const d=Math.abs(p.data[a+c]-p.data[b+c]);sum+=d;pixelMax=Math.max(pixelMax,d);max=Math.max(max,d);}if(pixelMax>v.threshold)above++;}return{samples:length,meanChannelDifference:sum/(length*4),maximumChannelDifference:max,aboveThreshold:above,ratio:above/length};}
return[await png(node,'tiled-preview.png'),json({leftRight:compare(true),topBottom:compare(false),threshold:v.threshold,channels:'RGBA',note:'边缘像素差用于检查接缝,不代表内部纹理重复效果。'},'seams.json')];
} }))();
function statistics(p){const means=[0,0,0],variance=[0,0,0];let count=0;for(let i=0;i<p.data.length;i+=4)if(p.data[i+3]){count++;for(let c=0;c<3;c++)means[c]+=p.data[i+c];}assert(count,'图片没有可见像素。');for(let c=0;c<3;c++)means[c]/=count;for(let i=0;i<p.data.length;i+=4)if(p.data[i+3])for(let c=0;c<3;c++)variance[c]+=(p.data[i+c]-means[c])**2;return{count,mean:means,std:variance.map((n)=>Math.sqrt(n/count))};}
export const color_transfer = (() => ({ fields:[num('strength','匹配强度',1,0,1,.05)],async run({images,values:v}){
assert(images.length===2,'请按原图、参考图顺序选择两张图片。');const node=source(images),p=pixels(node),reference=pixels(source([images[1]])),from=statistics(p),to=statistics(reference);let clipped=0;
for(let i=0;i<p.data.length;i+=4)if(p.data[i+3])for(let c=0;c<3;c++){const transformed=from.std[c]>.000001?(p.data[i+c]-from.mean[c])*to.std[c]/from.std[c]+to.mean[c]:to.mean[c],value=p.data[i+c]*(1-v.strength)+transformed*v.strength;if(value<0||value>255)clipped++;p.data[i+c]=value;}
node.getContext('2d').putImageData(p,0,0);return[await png(node,'color-matched.png'),json({source:from,reference:to,result:statistics(p),strength:v.strength,clippedChannelSamples:clipped,method:'逐RGB通道均值与标准差匹配;源零方差通道转为参考均值;保留Alpha。'},'color-transfer.json')];
} }))();
export const connected_regions = (() => ({ fields:[num('threshold','亮度阈值',128,0,255),choice('mode','检测对象',[['dark','深色区域'],['light','浅色区域']]),choice('connectivity','连接方式',[['4','4邻接'],['8','8邻接']]),num('minimum','最小面积(px)',4,1,100000)],async run({images,values:v}){
const node=source(images,1e6),p=pixels(node),count=p.width*p.height,foreground=new Uint8Array(count),seen=new Uint8Array(count),queue=new Int32Array(count),mask=new ImageData(p.width,p.height),regions=[];
for(let i=0;i<count;i++){const k=i*4,l=luminance(p.data[k],p.data[k+1],p.data[k+2]);foreground[i]=p.data[k+3]>=128&&(v.mode==='dark'?l<=v.threshold:l>=v.threshold)?1:0;mask.data.set([0,0,0,255],k);}
const offsets=v.connectivity==='8'?[[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[1,-1],[-1,1],[1,1]]:[[-1,0],[1,0],[0,-1],[0,1]];let totalComponents=0,keptPixels=0;
for(let i=0;i<count;i++)if(foreground[i]&&!seen[i]){let head=0,tail=1,minX=i%p.width,maxX=minX,minY=Math.floor(i/p.width),maxY=minY,sumX=0,sumY=0;queue[0]=i;seen[i]=1;
while(head<tail){const index=queue[head++],x=index%p.width,y=Math.floor(index/p.width);minX=Math.min(minX,x);maxX=Math.max(maxX,x);minY=Math.min(minY,y);maxY=Math.max(maxY,y);sumX+=x;sumY+=y;for(const[dx,dy]of offsets){const nx=x+dx,ny=y+dy,n=ny*p.width+nx;if(nx>=0&&nx<p.width&&ny>=0&&ny<p.height&&foreground[n]&&!seen[n]){seen[n]=1;queue[tail++]=n;}}}
totalComponents++;if(tail>=v.minimum){assert(regions.length<2000,'符合条件的区域超过2000个,请提高最小面积或调整阈值。');regions.push({id:regions.length+1,area:tail,x:minX,y:minY,width:maxX-minX+1,height:maxY-minY+1,centroid:[sumX/tail,sumY/tail]});keptPixels+=tail;for(let j=0;j<tail;j++)mask.data.set([255,255,255,255],queue[j]*4);}
}
const ctx=node.getContext('2d');ctx.strokeStyle='#ffce33';ctx.lineWidth=1;for(const r of regions)ctx.strokeRect(r.x+.5,r.y+.5,Math.max(0,r.width-1),Math.max(0,r.height-1));const maskCanvas=canvas(p.width,p.height);maskCanvas.getContext('2d').putImageData(mask,0,0);
return[await png(node,'regions.png'),await png(maskCanvas,'region-mask.png'),json({threshold:v.threshold,mode:v.mode,connectivity:Number(v.connectivity),minimumArea:v.minimum,totalComponents,keptPixels,regions},'regions.json')];
} }))();