-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathweb.html
More file actions
770 lines (666 loc) · 29.7 KB
/
Copy pathweb.html
File metadata and controls
770 lines (666 loc) · 29.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>SAM 3 Auto Selection</title>
<script src="https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js"></script>
<link rel="stylesheet" href="css/web.css" />
</head>
<body>
<div class="app-root">
<header>
<div class="logo">
<img src="icon/icon.png" alt="Logo" class="logo-icon" />
<span>SAM 3 <span class="accent">Auto Selection</span></span>
</div>
<div class="toolbar">
<div class="inputs-row">
<div>
<div class="field-label">后端模型地址</div>
<div class="server-input-wrapper">
<input
id="serverInput"
type="text"
value="http://localhost:8000"
spellcheck="false"
/>
<span id="serverStatus" class="status-dot offline"></span>
</div>
</div>
<div>
<div class="field-label">Sam3 模型地址</div>
<input
id="modelPathInput"
type="text"
value="D:/HF_DATA/sam3"
spellcheck="false"
placeholder="SAM 模型路径,例如 D:/HF_DATA/sam3"
/>
</div>
</div>
</div>
<div>
<button id="uploadButton">上传图片</button>
<button id="retryPrecomputeButton" disabled>重试预处理</button>
<input id="fileInput" type="file" accept="image/*" />
</div>
</header>
<main>
<div class="canvas-container" id="canvasContainer">
<div class="placeholder" id="placeholder">
<div class="hand">🖱️</div>
<div class="placeholder-text">UPLOAD TO START</div>
</div>
<div class="canvas-wrapper hidden" id="canvasWrapper">
<img id="baseImage" alt="Base" />
<img id="overlayImage" alt="" />
<img id="fixedOverlay" alt="" />
</div>
</div>
<aside class="side-panel">
<div class="panel-title">Mode</div>
<div class="mode-group">
<button class="mode-button active" id="modeHover" data-mode="hover">悬停选取</button>
<button class="mode-button" id="modeClick" data-mode="click">点击分割</button>
<button class="mode-button" id="modeText" data-mode="text">文字分割</button>
</div>
<div id="textControls" class="hidden">
<div class="field-label" style="margin-top: 8px">文本提示(英文逗号分隔)</div>
<textarea id="promptInput" placeholder="例如: car, wheel"></textarea>
<button id="runTextButton">运行文字分割</button>
</div>
<div>
<div class="field-label" style="margin-top: 8px">状态</div>
<div id="status">等待上传图片...</div>
</div>
</aside>
</main>
<div id="loadingOverlay" class="loading-overlay">
<div class="loading-content">
<img src="icon/icon.png" alt="Loading" class="loading-icon" />
<div class="loading-text">正在上传并处理图片...</div>
</div>
</div>
</div>
<script>
const serverInput = document.getElementById("serverInput");
const serverStatus = document.getElementById("serverStatus");
const modelPathInput = document.getElementById("modelPathInput");
const uploadButton = document.getElementById("uploadButton");
const retryPrecomputeButton = document.getElementById("retryPrecomputeButton");
const fileInput = document.getElementById("fileInput");
const baseImage = document.getElementById("baseImage");
const overlayImage = document.getElementById("overlayImage");
const fixedOverlay = document.getElementById("fixedOverlay");
const placeholder = document.getElementById("placeholder");
const canvasWrapper = document.getElementById("canvasWrapper");
const statusEl = document.getElementById("status");
const modeButtons = document.querySelectorAll(".mode-button");
const promptInput = document.getElementById("promptInput");
const runTextButton = document.getElementById("runTextButton");
const textControls = document.getElementById("textControls");
const loadingOverlay = document.getElementById("loadingOverlay");
const loadingText = loadingOverlay.querySelector(".loading-text");
let imageId = null;
let lastRequestId = 0;
let currentMode = "hover";
let lastHoverX = null;
let lastHoverY = null;
let hoverInFlight = false;
const HOVER_MIN_DISTANCE = 10;
// ONNX 悬停相关状态
let decoderSession = null;
let emb0 = null, emb1 = null, emb2 = null;
let shape0 = null, shape1 = null, shape2 = null;
let onnxReady = false;
let origH = null;
let origW = null;
let decoderTargetSize = 1024;
let hoverUseOnnx = false;
let lastImageDataUrl = null;
function apiBase() {
return serverInput.value.replace(/\/+$/, "");
}
function setServerOnline(online) {
serverStatus.classList.toggle("online", online);
serverStatus.classList.toggle("offline", !online);
}
function setLoading(isLoading, text) {
if (isLoading) {
loadingText.textContent = text || "正在上传并处理图片...";
loadingOverlay.classList.add("visible");
} else {
loadingOverlay.classList.remove("visible");
}
}
function clearOverlay() {
overlayImage.src = "";
overlayImage.style.display = "none";
fixedOverlay.src = "";
fixedOverlay.style.display = "none";
}
function flatten(arr) {
return arr.flat(Infinity);
}
async function ensureDecoderSession() {
if (decoderSession) return;
const url = `${apiBase()}/sam3_decoder.onnx`;
statusEl.textContent = "正在下载 ONNX 模型...";
decoderSession = await ort.InferenceSession.create(url);
statusEl.textContent = "ONNX 模型加载完成。";
}
async function decodePointONNX(normPoints, normLabels) {
if (!decoderSession || !onnxReady || !emb0) return null;
const pts = new Float32Array(flatten(normPoints));
const labelsFlat = flatten(normLabels).map((v) => BigInt(v));
const lbl = new BigInt64Array(labelsFlat);
const feeds = {};
for (const inp of decoderSession.inputNames) {
if (inp === "image_embedding_s0") {
feeds[inp] = new ort.Tensor("float32", emb0, shape0);
} else if (inp === "image_embedding_s1") {
feeds[inp] = new ort.Tensor("float32", emb1, shape1);
} else if (inp === "image_embedding_s2") {
feeds[inp] = new ort.Tensor("float32", emb2, shape2);
} else if (inp === "input_points") {
feeds[inp] = new ort.Tensor("float32", pts, [normPoints.length, normPoints[0].length, normPoints[0][0].length, 2]);
} else if (inp === "input_labels") {
feeds[inp] = new ort.Tensor("int64", lbl, [normLabels.length, normLabels[0].length, normLabels[0][0].length]);
}
}
const outputs = await decoderSession.run(feeds);
return outputs;
}
uploadButton.addEventListener("click", () => fileInput.click());
async function processImageDataUrl(dataUrl) {
lastImageDataUrl = dataUrl;
baseImage.src = dataUrl;
clearOverlay();
placeholder.classList.add("hidden");
canvasWrapper.classList.remove("hidden");
statusEl.textContent = "正在上传图片并预处理悬停特征...";
setLoading(true, "正在上传并预处理图片,请稍候...");
retryPrecomputeButton.disabled = true;
try {
const res = await fetch(`${apiBase()}/set_image`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
image_data: dataUrl,
model_path: modelPathInput.value.trim() || null,
}),
});
if (!res.ok) throw new Error(await res.text());
const json = await res.json();
imageId = json.image_id;
setServerOnline(true);
emb0 = emb1 = emb2 = null;
shape0 = shape1 = shape2 = null;
onnxReady = false;
hoverUseOnnx = false;
origH = null;
origW = null;
decoderTargetSize = 1024;
statusEl.textContent = "图片已上传,正在预处理悬停特征...";
await ensureDecoderSession();
const embRes = await fetch(`${apiBase()}/get_embeddings`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ image_id: imageId }),
});
if (!embRes.ok) throw new Error(await embRes.text());
const embJson = await embRes.json();
const [e0, e1, e2] = embJson.embeddings;
if (Array.isArray(embJson.original_sizes) && embJson.original_sizes.length > 0) {
const sz = embJson.original_sizes[0];
if (Array.isArray(sz) && sz.length >= 2) {
origH = sz[0];
origW = sz[1];
}
} else if (baseImage.naturalWidth && baseImage.naturalHeight) {
origH = baseImage.naturalHeight;
origW = baseImage.naturalWidth;
}
if (typeof embJson.target_size === "number" && embJson.target_size > 0) {
decoderTargetSize = embJson.target_size;
}
shape0 = [e0.length, e0[0].length, e0[0][0].length, e0[0][0][0].length];
shape1 = [e1.length, e1[0].length, e1[0][0].length, e1[0][0][0].length];
shape2 = [e2.length, e2[0].length, e2[0][0].length, e2[0][0][0].length];
emb0 = new Float32Array(flatten(e0));
emb1 = new Float32Array(flatten(e1));
emb2 = new Float32Array(flatten(e2));
onnxReady = true;
hoverUseOnnx = true;
statusEl.textContent = "图片上传并预处理完成,可以开始悬停选取。";
} catch (err) {
console.error(err);
setServerOnline(false);
statusEl.textContent = "上传或预处理失败,请检查后端地址、模型路径和 sam3_decoder.onnx。";
retryPrecomputeButton.disabled = !lastImageDataUrl;
} finally {
setLoading(false);
}
}
fileInput.addEventListener("change", async (event) => {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = async (e) => await processImageDataUrl(e.target.result);
reader.readAsDataURL(file);
});
retryPrecomputeButton.addEventListener("click", async () => {
if (!lastImageDataUrl) return;
await processImageDataUrl(lastImageDataUrl);
});
function getRelativeCoords(event) {
const rect = baseImage.getBoundingClientRect();
const naturalW = baseImage.naturalWidth;
const naturalH = baseImage.naturalHeight;
if (!naturalW || !naturalH) return { x: 0, y: 0 };
const scale = Math.min(rect.width / naturalW, rect.height / naturalH);
const displayW = naturalW * scale;
const displayH = naturalH * scale;
const offsetX = (rect.width - displayW) / 2;
const offsetY = (rect.height - displayH) / 2;
let x = event.clientX - rect.left - offsetX;
let y = event.clientY - rect.top - offsetY;
x = Math.max(0, Math.min(displayW, x));
y = Math.max(0, Math.min(displayH, y));
const origX = x / scale;
const origY = y / scale;
return { x: Math.round(origX), y: Math.round(origY) };
}
baseImage.addEventListener("mousemove", (event) => {
if (currentMode !== "hover") return;
if (!imageId) return;
if (!baseImage.naturalWidth || !baseImage.naturalHeight) return;
if (!onnxReady || !hoverUseOnnx) return;
const coords = getRelativeCoords(event);
if (lastHoverX !== null && lastHoverY !== null) {
const dx = coords.x - lastHoverX;
const dy = coords.y - lastHoverY;
const dist = Math.hypot(dx, dy);
if (dist < HOVER_MIN_DISTANCE) return;
}
lastHoverX = coords.x;
lastHoverY = coords.y;
handleHoverOnnx(coords.x, coords.y);
});
baseImage.addEventListener("click", (event) => {
if (!imageId) return;
const coords = getRelativeCoords(event);
if (currentMode === "click") {
requestSegmentPoint(coords.x, coords.y);
return;
}
if (currentMode === "hover") {
if (!overlayImage.src) return;
const fullW = baseImage.naturalWidth || overlayImage.naturalWidth;
const fullH = baseImage.naturalHeight || overlayImage.naturalHeight;
if (!fullW || !fullH) return;
const fixedCanvas = document.createElement("canvas");
fixedCanvas.width = fullW;
fixedCanvas.height = fullH;
const ctx = fixedCanvas.getContext("2d");
ctx.drawImage(overlayImage, 0, 0, fullW, fullH);
const imgData = ctx.getImageData(0, 0, fullW, fullH);
const data = imgData.data;
const size = fullW * fullH;
// 客户端固定逻辑:这里直接复制 Canvas 像素即可,因为现在 Hover 的视觉效果已经是最终效果
ctx.putImageData(imgData, 0, 0);
fixedOverlay.src = fixedCanvas.toDataURL("image/png");
fixedOverlay.style.display = "block";
overlayImage.src = "";
overlayImage.style.display = "none";
statusEl.textContent = `已固定选区,坐标 (${coords.x}, ${coords.y})`;
}
});
// -------------------------------------------------------------
// 前端图像处理算法库
// -------------------------------------------------------------
function keepLargestComponent(mask, w, h) {
const labels = new Int32Array(w * h).fill(0);
let currentLabel = 1;
const componentSizes = new Map();
// BFS 找连通域
for (let i = 0; i < w * h; i++) {
if (mask[i] && labels[i] === 0) {
let count = 0;
const queue = [i];
labels[i] = currentLabel;
let head = 0;
while(head < queue.length) {
const idx = queue[head++];
count++;
const x = idx % w;
const y = Math.floor(idx / w);
const neighbors = [];
if (y > 0) neighbors.push(idx - w);
if (y < h - 1) neighbors.push(idx + w);
if (x > 0) neighbors.push(idx - 1);
if (x < w - 1) neighbors.push(idx + 1);
for (const n_idx of neighbors) {
if (mask[n_idx] && labels[n_idx] === 0) {
labels[n_idx] = currentLabel;
queue.push(n_idx);
}
}
}
componentSizes.set(currentLabel, count);
currentLabel++;
}
}
let maxLabel = -1;
let maxSize = 0;
for (const [lbl, size] of componentSizes) {
if (size > maxSize) { maxSize = size; maxLabel = lbl; }
}
const result = new Uint8Array(w * h);
if (maxLabel !== -1) {
for (let i = 0; i < w * h; i++) {
if (labels[i] === maxLabel) result[i] = 1;
}
}
return result;
}
// FloodFill 填洞:从四边的背景灌水,灌不到的背景就是被前景包围的内部空洞,填为前景。
// 只填【完全封闭】的洞,不影响外轮廓的凹凸结构。
function fillHoles(mask, w, h) {
const floodMap = new Int32Array(w * h);
const queue = [];
for (let x = 0; x < w; x++) {
if (mask[0 * w + x] === 0) { floodMap[0 * w + x] = 2; queue.push(0 * w + x); }
if (mask[(h - 1) * w + x] === 0) { floodMap[(h - 1) * w + x] = 2; queue.push((h - 1) * w + x); }
}
for (let y = 1; y < h - 1; y++) {
if (mask[y * w + 0] === 0) { floodMap[y * w + 0] = 2; queue.push(y * w + 0); }
if (mask[y * w + (w - 1)] === 0) { floodMap[y * w + (w - 1)] = 2; queue.push(y * w + (w - 1)); }
}
let head = 0;
while(head < queue.length) {
const idx = queue[head++];
const x = idx % w;
const y = Math.floor(idx / w);
const neighbors = [];
if (y > 0) neighbors.push(idx - w);
if (y < h - 1) neighbors.push(idx + w);
if (x > 0) neighbors.push(idx - 1);
if (x < w - 1) neighbors.push(idx + 1);
for (const n_idx of neighbors) {
if (mask[n_idx] === 0 && floodMap[n_idx] === 0) {
floodMap[n_idx] = 2;
queue.push(n_idx);
}
}
}
const result = new Uint8Array(w * h);
for (let i = 0; i < w * h; i++) {
if (mask[i] === 1 || floodMap[i] === 0) {
result[i] = 1;
}
}
return result;
}
// 形态学膨胀(方形核,可分离:先水平后垂直;滑动计数 O(n),不受半径影响)
function dilateMask(mask, w, h, r) {
if (r <= 0) return mask;
const tmp = new Uint8Array(w * h);
for (let y = 0; y < h; y++) {
const row = y * w;
let count = 0;
for (let x = 0; x <= r && x < w; x++) count += mask[row + x];
for (let x = 0; x < w; x++) {
tmp[row + x] = count > 0 ? 1 : 0;
const out = x - r, add = x + r + 1;
if (out >= 0) count -= mask[row + out];
if (add < w) count += mask[row + add];
}
}
const res = new Uint8Array(w * h);
for (let x = 0; x < w; x++) {
let count = 0;
for (let y = 0; y <= r && y < h; y++) count += tmp[y * w + x];
for (let y = 0; y < h; y++) {
res[y * w + x] = count > 0 ? 1 : 0;
const out = y - r, add = y + r + 1;
if (out >= 0) count -= tmp[out * w + x];
if (add < h) count += tmp[add * w + x];
}
}
return res;
}
// 形态学闭运算 = 先膨胀后腐蚀;腐蚀用 De Morgan:erode(M) = ¬dilate(¬M)。
// 作用:填平小缺口/凹槽、桥接细微断裂(如整车选区里漏掉的一小块轮胎),整体大小基本不变。
function closeMask(mask, w, h, r) {
if (r <= 0) return mask;
const dil = dilateMask(mask, w, h, r);
const inv = new Uint8Array(w * h);
for (let i = 0; i < w * h; i++) inv[i] = dil[i] ? 0 : 1;
const invDil = dilateMask(inv, w, h, r);
const res = new Uint8Array(w * h);
for (let i = 0; i < w * h; i++) res[i] = invDil[i] ? 0 : 1;
return res;
}
function bilinearUpscale(srcData, srcW, srcH, dstW, dstH) {
const dstData = new Float32Array(dstW * dstH);
const xRatio = srcW / dstW;
const yRatio = srcH / dstH;
for (let y = 0; y < dstH; y++) {
for (let x = 0; x < dstW; x++) {
const srcX = x * xRatio;
const srcY = y * yRatio;
const x0 = Math.floor(srcX);
const y0 = Math.floor(srcY);
const x1 = Math.min(x0 + 1, srcW - 1);
const y1 = Math.min(y0 + 1, srcH - 1);
const dx = srcX - x0;
const dy = srcY - y0;
const idx00 = y0 * srcW + x0;
const idx10 = y0 * srcW + x1;
const idx01 = y1 * srcW + x0;
const idx11 = y1 * srcW + x1;
const val00 = srcData[idx00];
const val10 = srcData[idx10];
const val01 = srcData[idx01];
const val11 = srcData[idx11];
const valTop = val00 * (1 - dx) + val10 * dx;
const valBot = val01 * (1 - dx) + val11 * dx;
const val = valTop * (1 - dy) + valBot * dy;
dstData[y * dstW + x] = val;
}
}
return dstData;
}
async function handleHoverOnnx(x, y) {
if (!imageId) return;
if (hoverInFlight) return;
if (!onnxReady || !emb0 || !emb1 || !emb2) return;
if (!origH || !origW || !decoderTargetSize) return;
hoverInFlight = true;
try {
const sx = decoderTargetSize / origW;
const sy = decoderTargetSize / origH;
const nx = x * sx;
const ny = y * sy;
const normPoints = [[[[nx, ny]]]];
const normLabels = [[[1]]];
const out = await decodePointONNX(normPoints, normLabels);
if (!out || !out["pred_masks"]) {
hoverInFlight = false;
return;
}
const predMasks = out["pred_masks"]; // [1, 1, numMasks, H, W](低分辨率 logits)
const iouScores = out["iou_scores"]; // [1, 1, numMasks]
const numMasks = predMasks.dims[2];
const srcH = predMasks.dims[3]; // 解码器输出分辨率(动态读取,当前模型约 288)
const srcW = predMasks.dims[4];
// 多候选 mask 中按 IoU 选最优:通常是“整体物体”那个 → 选区完整,
// 且在物体内各点之间一致 → 悬停时自然稳定(参考工具的手感来源)。
let bestIdx = 0;
if (iouScores && iouScores.data && iouScores.data.length >= numMasks) {
let bestScore = -Infinity;
for (let m = 0; m < numMasks; m++) {
if (iouScores.data[m] > bestScore) {
bestScore = iouScores.data[m];
bestIdx = m;
}
}
}
const planeSize = srcH * srcW;
// 取出最优 mask 这一层的 logits(subarray 是视图,零拷贝)
const srcData = predMasks.data.subarray(bestIdx * planeSize, (bestIdx + 1) * planeSize);
// --- 处理流水线 (v11: 完整对齐后端 post_process_masks,在显示分辨率上做) ---
// 顺序与后端 segment_point 完全一致:
// 先把 256 的【原始 logits】双线性上采样到显示分辨率,再阈值 → 平滑边界;
// 然后在高分辨率上做「最大连通域」去噪 + 「FloodFill 填洞」 → 实心干净的 mask。
// 关键:不再用 -10 硬砍连通域外的 logit(那会让边界按 256 网格阶梯化、产生锯齿)。
// 1. 计算显示分辨率
const maxDim = 1024;
const imgAspect = (baseImage.naturalWidth || srcW) / (baseImage.naturalHeight || srcH);
let dstW, dstH;
if (imgAspect > 1) {
dstW = maxDim;
dstH = Math.round(maxDim / imgAspect);
} else {
dstH = maxDim;
dstW = Math.round(maxDim * imgAspect);
}
// 2. 上采样【原始 logits】(不做任何硬填),阈值得到平滑边界
const highResLogits = bilinearUpscale(srcData, srcW, srcH, dstW, dstH);
let highResMask = new Uint8Array(dstW * dstH);
for (let i = 0; i < dstW * dstH; i++) {
highResMask[i] = highResLogits[i] > 0.0 ? 1 : 0;
}
// 3. 闭运算:补回整体选区里漏掉的小块、桥接细微断裂(如整车里漏选的一小段轮胎)。
// 放在「最大连通域」之前,好让近乎断开的小块先被桥接回主体、不被当噪点丢掉。
// 半径越大越能「封住」深凹口的口子(封住后第 4 步 fillHoles 就能把整条深槽填满),
// 代价是尖角会更圆。dilateMask 是 O(n),调大半径不增加计算量。
// —— 这是补全选区凹口的【唯一旋钮】:还漏就调大(如 /100),凹口被过度填平就调小。
// 注意:闭运算是扩张型运算,只填凹陷、不磨凸出尖角,所以放心加大。
const closeR = Math.max(3, Math.round(dstW / 140));
highResMask = closeMask(highResMask, dstW, dstH, closeR);
// 4. 高分辨率去噪 + 填洞(对应后端 connectedComponents + floodFill)
highResMask = keepLargestComponent(highResMask, dstW, dstH);
highResMask = fillHoles(highResMask, dstW, dstH);
// 5. 准备渲染缓冲
const imgData = new ImageData(dstW, dstH);
const pixels = imgData.data;
// 6. 渲染
for (let y = 0; y < dstH; y++) {
for (let x = 0; x < dstW; x++) {
const idx = y * dstW + x;
if (highResMask[idx] === 1) {
const pIdx = idx * 4;
// 简单的 4 邻域边缘检测
let isBorder = false;
if (x === 0 || x === dstW - 1 || y === 0 || y === dstH - 1) {
isBorder = true;
} else {
if (highResMask[idx - 1] === 0 ||
highResMask[idx + 1] === 0 ||
highResMask[idx - dstW] === 0 ||
highResMask[idx + dstW] === 0) {
isBorder = true;
}
}
if (isBorder) {
pixels[pIdx] = 255;
pixels[pIdx + 1] = 255;
pixels[pIdx + 2] = 255;
pixels[pIdx + 3] = 255;
} else {
pixels[pIdx] = 30;
pixels[pIdx + 1] = 144;
pixels[pIdx + 2] = 255;
pixels[pIdx + 3] = 166;
}
}
}
}
const maskCanvas = document.createElement("canvas");
maskCanvas.width = dstW;
maskCanvas.height = dstH;
const mctx = maskCanvas.getContext("2d");
mctx.putImageData(imgData, 0, 0);
const fullW = baseImage.naturalWidth || dstW;
const fullH = baseImage.naturalHeight || dstH;
const fullCanvas = document.createElement("canvas");
fullCanvas.width = fullW;
fullCanvas.height = fullH;
const fctx = fullCanvas.getContext("2d");
fctx.imageSmoothingEnabled = true;
fctx.imageSmoothingQuality = "high";
fctx.drawImage(maskCanvas, 0, 0, fullW, fullH);
overlayImage.src = fullCanvas.toDataURL("image/png");
overlayImage.style.display = "block";
} catch (err) {
console.error(err);
} finally {
hoverInFlight = false;
}
}
async function requestSegmentPoint(x, y) {
const currentRequestId = ++lastRequestId;
statusEl.textContent = `点击坐标: (${x}, ${y}),请求中...`;
try {
const res = await fetch(`${apiBase()}/segment_point`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ image_id: imageId, x, y }),
});
if (!res.ok) {
statusEl.textContent = "当前点未检测到目标。";
clearOverlay();
return;
}
const json = await res.json();
if (currentRequestId !== lastRequestId) return;
overlayImage.src = json.image;
overlayImage.style.display = "block";
statusEl.textContent = `已更新选区,坐标 (${x}, ${y})`;
} catch (err) {
console.error(err);
setServerOnline(false);
statusEl.textContent = "请求失败,请检查后端。";
}
}
modeButtons.forEach((btn) => {
btn.addEventListener("click", () => {
modeButtons.forEach((b) => b.classList.remove("active"));
btn.classList.add("active");
currentMode = btn.dataset.mode;
lastRequestId++;
hoverInFlight = false;
textControls.classList.toggle("hidden", currentMode !== "text");
clearOverlay();
if (currentMode === "text") {
statusEl.textContent = "输入文本提示后点击“运行文字分割”。";
}
});
});
runTextButton.addEventListener("click", async () => {
if (!imageId) { statusEl.textContent = "请先上传图片。"; return; }
const text = promptInput.value.trim();
if (!text) { statusEl.textContent = "文本提示不能为空。"; return; }
statusEl.textContent = "文字分割中...";
try {
const res = await fetch(`${apiBase()}/segment_text`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ image_id: imageId, text }),
});
if (!res.ok) { statusEl.textContent = "文字分割失败,请检查后端日志。"; return; }
const json = await res.json();
overlayImage.src = json.image;
overlayImage.style.display = "block";
statusEl.textContent = "文字分割完成。";
} catch (err) {
console.error(err);
setServerOnline(false);
statusEl.textContent = "请求失败,请检查后端。";
}
});
</script>
</body>
</html>