CarterBenjamin commited on
Commit
b7f23c8
·
verified ·
1 Parent(s): 51a4503

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ examples/out_sample01.png filter=lfs diff=lfs merge=lfs -text
37
+ examples/out_sample02.png filter=lfs diff=lfs merge=lfs -text
38
+ examples/sample01.png filter=lfs diff=lfs merge=lfs -text
39
+ examples/sample02.png filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,10 +1,49 @@
1
  ---
2
- title: Cs2 Detect Static
3
- emoji: 📈
4
- colorFrom: pink
5
- colorTo: pink
6
  sdk: static
7
  pinned: false
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: CS2 目标检测 demo
3
+ emoji: 🎯
4
+ colorFrom: indigo
5
+ colorTo: gray
6
  sdk: static
7
  pinned: false
8
+ license: other
9
+ short_description: 浏览器里跑 ONNX 的 CS2 检测 demo
10
  ---
11
 
12
+ # CS2 目标检测 demo(纯浏览器推理)
13
+
14
+ 打开页面,选一张 CS2 截图,它会框出**身体与头**并在表里给出像素框高 —— 全部在你自己浏览器里算
15
+ (onnxruntime-web / WASM),图片不上传、不经服务器。
16
+
17
+ ## 三种模型
18
+
19
+ | 选项 | 来源 | 说明 |
20
+ |---|---|---|
21
+ | 本站自带 | 本项目自训(head / body 两类,320×320) | 开箱即用,无需任何设置 |
22
+ | Vombit `yolo11n_cs2` | [Vombit/yolo11n_cs2](https://huggingface.co/Vombit/yolo11n_cs2) | gated 仓库,四个类别 `c / ch / t / th` |
23
+ | Vombit `yolo11s_cs2` | [Vombit/yolo11s_cs2](https://huggingface.co/Vombit/yolo11s_cs2) | 同上,更准更慢 |
24
+
25
+ 后两个要用,需要两件事:
26
+
27
+ 1. 你的 HF 账号先在仓库页点 **Agree and access repository**;
28
+ 2. 在页面左侧填一个你自己的 **read token**(https://huggingface.co/settings/tokens)。
29
+
30
+ 页面会带着这个 token 直接去 `huggingface.co` 取权重 —— 本 Space **不转发、不存储、不重新分发**
31
+ gated 权重,token 也只用于这一次请求。这也是为什么这里没有把权重直接放进仓库。
32
+
33
+ ## 怎么看结果
34
+
35
+ - **检测明细**里的「高(px)」是关键:`40px` 左右 ≈ 游戏里二十米外的敌人;`<12px` 时基本只剩身体框,
36
+ 头会消失 —— 那是物理极限(320 输入下 12px 的目标只剩 3~4 个像素),不是模型差。
37
+ - 两个类别体系不一样:自训模型只有 `head/body`;Vombit 是 `c/ch/t/th`(CT 身体、CT 头、T 身体、T 头)。
38
+
39
+ ## 实现细节
40
+
41
+ - 输入按模型自身尺寸做 letterbox(补 114 灰边),输出框再反算回原图坐标
42
+ - 解码支持 ultralytics v8 导出:`[1, 4+nc, N]`,逐类做 NMS
43
+ - 静态 Space:没有后端进程,`sdk: static`,onnxruntime-web 从 jsdelivr 加载
44
+
45
+ ## 本地跑
46
+
47
+ ```bash
48
+ python -m http.server 8000 # 然后开 http://localhost:8000
49
+ ```
__pycache__/app.cpython-312.pyc ADDED
Binary file (14.4 kB). View file
 
app.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CS2 目标检测 demo —— Vombit/yolo11n_cs2 & yolo11s_cs2 的在线试用页。
2
+
3
+ 为什么需要这个 Space:那两个仓库是 gated(要点 Agree 才给下),
4
+ 在 Space 里用 Secret 里的 HF_TOKEN 去拉权重,就等于"在你账号授权下用",
5
+ 页面上任何人都能试,但权重本身不对外重发。
6
+
7
+ 判定口径(和本地 tools/rank_models.py 一致):
8
+ 只看"送进网络后的像素"——同一张图缩放到模型输入尺寸再推理。
9
+ Vombit 的类别表是 ['c','ch','t','th']:
10
+ c = Counter-Terrorist 身体, ch = CT 头, t = T 身体, th = T 头
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ from typing import Dict, List, Tuple
17
+
18
+ import numpy as np
19
+ import onnxruntime as ort
20
+ from PIL import Image, ImageDraw
21
+ from huggingface_hub import hf_hub_download
22
+
23
+ # ---------------------------------------------------------------- 模型清单
24
+
25
+ MODELS: Dict[str, Dict] = {
26
+ "yolo11n_cs2(快,约 5 MB)": {
27
+ "repo": "Vombit/yolo11n_cs2",
28
+ "file": "yolo11n_cs2.onnx",
29
+ "labels": ["c", "ch", "t", "th"],
30
+ },
31
+ "yolo11s_cs2(准,约 18 MB)": {
32
+ "repo": "Vombit/yolo11s_cs2",
33
+ "file": "yolo11s_cs2.onnx",
34
+ "labels": ["c", "ch", "t", "th"],
35
+ },
36
+ }
37
+
38
+ ZH = {"c": "CT 身体", "ch": "CT 头", "t": "T 身体", "th": "T 头"}
39
+ COLORS = {"c": (120, 170, 255), "ch": (255, 90, 80), "t": (255, 200, 90), "th": (255, 120, 220)}
40
+
41
+ _SESSIONS: Dict[str, Tuple[ort.InferenceSession, Tuple[int, int]]] = {}
42
+
43
+
44
+ def token() -> str | None:
45
+ for key in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN", "HUGGINGFACEHUB_API_TOKEN"):
46
+ v = os.environ.get(key)
47
+ if v:
48
+ return v.strip()
49
+ return None
50
+
51
+
52
+ def get_session(name: str):
53
+ """按需加载并缓存推理会话,返回 (session, (高, 宽))。
54
+
55
+ 本地调试时可以设 `LOCAL_MODEL_DIR` 指向一个放着同名 .onnx 的目录,
56
+ 这样不用 HF token 也能把整条链路跑通(Space 上用不到,只是自测方便)。
57
+ """
58
+ if name in _SESSIONS:
59
+ return _SESSIONS[name]
60
+ spec = MODELS[name]
61
+ local = os.environ.get("LOCAL_MODEL_DIR")
62
+ candidate = os.path.join(local, spec["file"]) if local else ""
63
+ if candidate and os.path.isfile(candidate):
64
+ path = candidate
65
+ else:
66
+ path = hf_hub_download(
67
+ repo_id=spec["repo"],
68
+ filename=spec["file"],
69
+ token=token(),
70
+ )
71
+ sess = ort.InferenceSession(path, providers=["CPUExecutionProvider"])
72
+ shape = sess.get_inputs()[0].shape
73
+ h, w = int(shape[2]), int(shape[3])
74
+ _SESSIONS[name] = (sess, (h, w))
75
+ return _SESSIONS[name]
76
+
77
+
78
+ # ---------------------------------------------------------------- 预处理
79
+
80
+
81
+ def letterbox(img: Image.Image, size: Tuple[int, int], color: int = 114):
82
+ """等比缩放 + 居中补边,返回 (图, 缩放比, 左, 上)。"""
83
+ tw, th = size[1], size[0]
84
+ w, h = img.size
85
+ r = min(tw / w, th / h)
86
+ nw, nh = max(1, int(round(w * r))), max(1, int(round(h * r)))
87
+ resized = img.resize((nw, nh), Image.BILINEAR)
88
+ canvas = Image.new("RGB", (tw, th), (color, color, color))
89
+ left, top = (tw - nw) // 2, (th - nh) // 2
90
+ canvas.paste(resized, (left, top))
91
+ return canvas, r, left, top
92
+
93
+
94
+ def to_tensor(img: Image.Image) -> np.ndarray:
95
+ arr = np.asarray(img, dtype=np.float32) / 255.0
96
+ arr = arr[:, :, ::-1] # RGB -> BGR,ultralytics 导出就是这样训的
97
+ return np.ascontiguousarray(arr.transpose(2, 0, 1)[None, ...])
98
+
99
+
100
+ # ---------------------------------------------------------------- 后处理
101
+
102
+
103
+ def iou(a: np.ndarray, b: np.ndarray) -> np.ndarray:
104
+ x1 = np.maximum(a[0], b[:, 0])
105
+ y1 = np.maximum(a[1], b[:, 1])
106
+ x2 = np.minimum(a[2], b[:, 2])
107
+ y2 = np.minimum(a[3], b[:, 3])
108
+ inter = np.clip(x2 - x1, 0, None) * np.clip(y2 - y1, 0, None)
109
+ area_a = (a[2] - a[0]) * (a[3] - a[1])
110
+ area_b = (b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1])
111
+ return inter / np.maximum(area_a + area_b - inter, 1e-9)
112
+
113
+
114
+ def nms(boxes: np.ndarray, scores: np.ndarray, thr: float) -> List[int]:
115
+ order = scores.argsort()[::-1]
116
+ keep: List[int] = []
117
+ while order.size:
118
+ i = int(order[0])
119
+ keep.append(i)
120
+ if order.size == 1:
121
+ break
122
+ rest = order[1:]
123
+ order = rest[iou(boxes[i], boxes[rest]) <= thr]
124
+ return keep
125
+
126
+
127
+ def decode(out: np.ndarray, nc: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
128
+ """把 ultralytics v8 导出([1, 4+nc, N])解析成 boxes/scores/cls。"""
129
+ p = out[0]
130
+ if p.ndim != 2:
131
+ p = p.reshape(p.shape[0], -1)
132
+ if p.shape[0] > p.shape[1]: # 转置成 [4+nc, N]
133
+ p = p.T
134
+ if p.shape[0] == 4 + nc:
135
+ boxes = p[0:4].T
136
+ cls_scores = p[4:4 + nc].T
137
+ elif p.shape[0] == 6: # 端到端导出(xyxy, score, cls)
138
+ return p[:, 0:4], p[:, 4], p[:, 5].astype(int)
139
+ else:
140
+ raise ValueError(f"看不懂的输出形状 {p.shape}(nc={nc})")
141
+ cls_ids = cls_scores.argmax(axis=1)
142
+ scores = cls_scores[np.arange(len(cls_ids)), cls_ids]
143
+ cx, cy, w, h = boxes.T
144
+ return np.stack([cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2], axis=1), scores, cls_ids
145
+
146
+
147
+ def detect(img: Image.Image, model_name: str, conf: float, iou_thr: float):
148
+ sess, (mh, mw) = get_session(model_name)
149
+ labels = MODELS[model_name]["labels"]
150
+ boxed, r, left, top = letterbox(img, (mh, mw))
151
+ out = sess.run(None, {sess.get_inputs()[0].name: to_tensor(boxed)})[0]
152
+ xyxy, scores, cls = decode(out, len(labels))
153
+
154
+ mask = scores >= conf
155
+ xyxy, scores, cls = xyxy[mask], scores[mask], cls[mask]
156
+ keep: List[int] = []
157
+ for c in np.unique(cls):
158
+ idx = np.where(cls == c)[0]
159
+ for k in nms(xyxy[idx], scores[idx], iou_thr):
160
+ keep.append(int(idx[k]))
161
+ keep.sort(key=lambda i: -scores[i])
162
+
163
+ # 反 letterbox:先减补边再除比例
164
+ px = np.stack([(xyxy[:, 0] - left) / r, (xyxy[:, 1] - top) / r,
165
+ (xyxy[:, 2] - left) / r, (xyxy[:, 3] - top) / r], axis=1)
166
+
167
+ draw = ImageDraw.Draw(img)
168
+ rows = []
169
+ for i in keep:
170
+ if i >= len(px):
171
+ continue
172
+ x1, y1, x2, y2 = [float(v) for v in px[i]]
173
+ name = labels[int(cls[i])] if int(cls[i]) < len(labels) else str(int(cls[i]))
174
+ color = COLORS.get(name, (255, 255, 255))
175
+ draw.rectangle([x1, y1, x2, y2], outline=color, width=2)
176
+ draw.text((x1 + 2, max(0, y1 - 12)), f"{ZH.get(name, name)} {scores[i]:.2f}", fill=color)
177
+ rows.append([
178
+ ZH.get(name, name),
179
+ round(float(scores[i]), 3),
180
+ [round(v, 1) for v in (x1, y1, x2, y2)],
181
+ round(y2 - y1, 1),
182
+ ])
183
+ return img, rows
184
+
185
+
186
+ # ---------------------------------------------------------------- 界面
187
+
188
+
189
+ def run(image, model_name: str, conf: float, iou_thr: float):
190
+ import gradio as gr
191
+
192
+ if image is None:
193
+ return None, []
194
+ img = image.convert("RGB").copy()
195
+ try:
196
+ return detect(img, model_name, conf, iou_thr)
197
+ except Exception as exc: # 权重拉不下来 / 形状不认识,都在这里暴露
198
+ raise gr.Error(f"{type(exc).__name__}: {exc}") from exc
199
+
200
+
201
+ def build_ui():
202
+ import gradio as gr
203
+
204
+ with gr.Blocks(title="CS2 检测 demo (Vombit yolo11)") as demo:
205
+ gr.Markdown(
206
+ "## CS2 目标检测 demo\n"
207
+ "上传一张 CS2 截图(或直接用示例图),看模型框出 **CT / T 的身体与头**。\n\n"
208
+ "模型来自 `Vombit/yolo11n_cs2`、`Vombit/yolo11s_cs2`(gated 仓库,"
209
+ "本站用 Secret 里的 HF_TOKEN 读取,不重发权重)。\n\n"
210
+ "**怎么看结果**:先看「检测明细」里有没有框、类别对不对;"
211
+ "再看「高(px)」——40px 左右约等于游戏里 20 米外的敌人,"
212
+ "小于 12px 基本就该只剩身体框了。"
213
+ )
214
+ with gr.Row():
215
+ with gr.Column():
216
+ inp = gr.Image(type="pil", label="输入图")
217
+ mdl = gr.Dropdown(list(MODELS), value=list(MODELS)[0], label="模型")
218
+ cf = gr.Slider(0.05, 0.9, value=0.35, step=0.05, label="置信度阈值")
219
+ it = gr.Slider(0.1, 0.9, value=0.45, step=0.05, label="NMS IoU")
220
+ btn = gr.Button("检测", variant="primary")
221
+ with gr.Column():
222
+ out = gr.Image(type="pil", label="结果")
223
+ tbl = gr.Dataframe(headers=["类别", "置信度", "框", "高(px)"], label="检测明细")
224
+ gr.Examples(
225
+ examples=[["examples/sample01.png"]],
226
+ inputs=[inp],
227
+ label="示例(把 CS2 截图放到 examples/ 里就会出现在这里)",
228
+ )
229
+ btn.click(run, [inp, mdl, cf, it], [out, tbl])
230
+ inp.change(run, [inp, mdl, cf, it], [out, tbl])
231
+ return demo
232
+
233
+
234
+ if __name__ == "__main__":
235
+ build_ui().launch()
cs2.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fae71fcc685510ac82855b321181058855424a73dc9b036de1e111d4faed9ad1
3
+ size 12621111
examples/out_sample01.png ADDED

Git LFS Details

  • SHA256: 21a510cf1d81c656312e885967771a23cf7145855fcc2663411812793cf88d0c
  • Pointer size: 131 Bytes
  • Size of remote file: 129 kB
examples/out_sample02.png ADDED

Git LFS Details

  • SHA256: 0aec8b9d2cc28a87126bd42115350e5331dd3a04f919aa5a40fe199883908df7
  • Pointer size: 131 Bytes
  • Size of remote file: 165 kB
examples/sample01.png ADDED

Git LFS Details

  • SHA256: 072f01b7cbb4040f9319a6c64c1c62b7d76fa505d1513977b4c81945acf42264
  • Pointer size: 131 Bytes
  • Size of remote file: 144 kB
examples/sample02.png ADDED

Git LFS Details

  • SHA256: a8a30a14f587e4113374687eb6e84278688461f67e7ad72b4482e52191b12c72
  • Pointer size: 131 Bytes
  • Size of remote file: 181 kB
index.html CHANGED
@@ -1,19 +1,294 @@
1
  <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  </html>
 
1
  <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>CS2 目标检测 demo(浏览器内推理)</title>
7
+ <style>
8
+ :root { --bg:#14151a; --card:#1d1f26; --fg:#e8e8e8; --dim:#8a8f98; --ok:#39ff88; --bad:#ff5b52; }
9
+ * { box-sizing: border-box; }
10
+ body { margin:0; background:var(--bg); color:var(--fg); font:14px/1.6 "Microsoft YaHei UI",system-ui,sans-serif; }
11
+ header { padding:18px 22px 8px; }
12
+ h1 { margin:0 0 4px; font-size:18px; }
13
+ .sub { color:var(--dim); font-size:13px; }
14
+ main { display:grid; grid-template-columns: 340px 1fr; gap:18px; padding:14px 22px 40px; }
15
+ @media (max-width: 900px) { main { grid-template-columns: 1fr; } }
16
+ .card { background:var(--card); border:1px solid #2a2d36; border-radius:10px; padding:14px; }
17
+ label { display:block; color:var(--dim); font-size:12px; margin:10px 0 4px; }
18
+ select,input[type=text],input[type=number] { width:100%; background:#0f1014; color:var(--fg);
19
+ border:1px solid #2f333d; border-radius:6px; padding:7px 9px; font:inherit; }
20
+ input[type=range]{ width:100%; }
21
+ button { background:#2b2f39; color:var(--fg); border:1px solid #3a3f4b; border-radius:6px;
22
+ padding:9px 14px; font:inherit; cursor:pointer; }
23
+ button.primary { background:var(--ok); color:#0b1410; border-color:var(--ok); font-weight:600; }
24
+ button:disabled { opacity:.45; cursor:not-allowed; }
25
+ .row { display:flex; gap:8px; margin-top:12px; }
26
+ .row > * { flex:1; }
27
+ canvas { max-width:100%; border-radius:8px; display:block; background:#0b0c10; }
28
+ table { width:100%; border-collapse:collapse; font-size:13px; margin-top:10px; }
29
+ th,td { text-align:left; padding:5px 6px; border-bottom:1px solid #262932; }
30
+ th { color:var(--dim); font-weight:500; }
31
+ #log { color:var(--dim); font-size:12px; margin-top:10px; white-space:pre-wrap; }
32
+ .hint { color:#e8c05a; font-size:12px; margin-top:8px; }
33
+ a { color:#7fd1ff; }
34
+ </style>
35
+ <script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.19.2/dist/ort.min.js"></script>
36
+ </head>
37
+ <body>
38
+ <header>
39
+ <h1>CS2 目标检测 demo</h1>
40
+ <div class="sub">纯浏览器推理(onnxruntime-web / WASM),不经过服务器,图片不上传。</div>
41
+ </header>
42
+
43
+ <main>
44
+ <section class="card">
45
+ <label>选择输入图</label>
46
+ <input id="file" type="file" accept="image/*" />
47
+ <label>或试一张示例</label>
48
+ <div class="row">
49
+ <button id="ex1">中距离</button>
50
+ <button id="ex2">贴脸</button>
51
+ </div>
52
+
53
+ <label>模型</label>
54
+ <select id="model">
55
+ <option value="local">本站自带(自训 head/body,12 MB)</option>
56
+ <option value="11n">Vombit yolo11n_cs2(需 token)</option>
57
+ <option value="11s">Vombit yolo11s_cs2(需 token)</option>
58
+ </select>
59
+
60
+ <label>HF token(只在用 Vombit 那两个 gated 模型时填)</label>
61
+ <input id="token" type="text" placeholder="hf_xxx(只留在你浏览器里)" autocomplete="off" />
62
+ <div class="hint">这两个仓库是 gated:页面直接带你的 token 去 huggingface.co 取权重,
63
+ 本站不转发、不存储。token 只用于这一次请求。</div>
64
+
65
+ <label>置信度阈值 <span id="cfv">0.35</span></label>
66
+ <input id="conf" type="range" min="0.05" max="0.9" step="0.05" value="0.35" />
67
+
68
+ <label>NMS IoU <span id="iouv">0.45</span></label>
69
+ <input id="iou" type="range" min="0.1" max="0.9" step="0.05" value="0.45" />
70
+
71
+ <div class="row">
72
+ <button class="primary" id="run" disabled>检测</button>
73
+ </div>
74
+ <div id="log">等模型就绪…</div>
75
+ </section>
76
+
77
+ <section class="card">
78
+ <canvas id="cv" width="640" height="640"></canvas>
79
+ <table id="tbl">
80
+ <thead><tr><th>类别</th><th>置信度</th><th>框 (x1,y1,x2,y2)</th><th>高(px)</th></tr></thead>
81
+ <tbody></tbody>
82
+ </table>
83
+ </section>
84
+ </main>
85
+
86
+ <script>
87
+ const MODELS = {
88
+ local: { url: "cs2.onnx", labels: ["head", "body"], size: [320, 320] },
89
+ "11n": { url: "https://huggingface.co/Vombit/yolo11n_cs2/resolve/main/yolo11n_cs2.onnx",
90
+ labels: ["c", "ch", "t", "th"], size: [640, 640], gated: true },
91
+ "11s": { url: "https://huggingface.co/Vombit/yolo11s_cs2/resolve/main/yolo11s_cs2.onnx",
92
+ labels: ["c", "ch", "t", "th"], size: [640, 640], gated: true },
93
+ };
94
+ const ZH = { head:"头部", body:"身体", c:"CT 身体", ch:"CT 头", t:"T 身体", th:"T 头" };
95
+ const COLORS = { head:"#ff5b52", body:"#7fd1ff", c:"#7fd1ff", ch:"#ff5b52", t:"#e8c05a", th:"#ff78dc" };
96
+
97
+ ort.env.wasm.numThreads = 1;
98
+ ort.env.wasm.wasmPaths = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.19.2/dist/";
99
+
100
+ const $ = (id) => document.getElementById(id);
101
+ const cv = $("cv"), ctx = cv.getContext("2d");
102
+ const sessions = {};
103
+ let img = null;
104
+ let meta = null; // {mw, mh, labels}
105
+
106
+ function log(s) { $("log").textContent = s; }
107
+
108
+ async function getSession(key, token) {
109
+ if (sessions[key]) return sessions[key];
110
+ const spec = MODELS[key];
111
+ log("下载模型 " + key + " …");
112
+ const headers = spec.gated && token ? { Authorization: "Bearer " + token } : {};
113
+ const res = await fetch(spec.url, { headers });
114
+ if (!res.ok) throw new Error(`取模型失败 HTTP ${res.status}` + (res.status === 401 ? "(需要 token,或先在网页点 Agree)" : ""));
115
+ const buf = new Uint8Array(await res.arrayBuffer());
116
+ log("模型 " + key + " 到手," + (buf.length / 1048576).toFixed(1) + " MB,正在初始化…");
117
+ const sess = await ort.InferenceSession.create(buf, { executionProviders: ["wasm"] });
118
+ const inputName = sess.inputNames[0];
119
+ // Vombit 那两个是动态输入(height/width 是符号),所以用预设尺寸;输出 N 由运行时给的真实 dims 决定。
120
+ const [mw, mh] = spec.size;
121
+ sessions[key] = { sess, inputName, mw, mh };
122
+ return sessions[key];
123
+ }
124
+
125
+ function drawBase() {
126
+ if (!img) return;
127
+ cv.width = img.width; cv.height = img.height;
128
+ ctx.drawImage(img, 0, 0);
129
+ }
130
+
131
+ function letterboxTo(size) { // 返回 {canvas, r, left, top}
132
+ const [mw, mh] = size;
133
+ const r = Math.min(mw / img.width, mh / img.height);
134
+ const nw = Math.max(1, Math.round(img.width * r));
135
+ const nh = Math.max(1, Math.round(img.height * r));
136
+ const c = document.createElement("canvas");
137
+ c.width = mw; c.height = mh;
138
+ const g = c.getContext("2d");
139
+ g.fillStyle = "rgb(114,114,114)";
140
+ g.fillRect(0, 0, mw, mh);
141
+ const left = Math.floor((mw - nw) / 2), top = Math.floor((mh - nh) / 2);
142
+ g.drawImage(img, left, top, nw, nh);
143
+ return { canvas: c, r, left, top };
144
+ }
145
+
146
+ function toTensor(canvas, mw, mh) {
147
+ const d = canvas.getContext("2d").getImageData(0, 0, mw, mh).data;
148
+ const n = mw * mh;
149
+ const out = new Float32Array(3 * n);
150
+ for (let i = 0; i < n; i++) {
151
+ const p = i * 4;
152
+ out[i] = d[p + 2] / 255; // B
153
+ out[n + i] = d[p + 1] / 255; // G
154
+ out[2 * n + i] = d[p] / 255; // R
155
+ }
156
+ return new ort.Tensor("float32", out, [1, 3, mh, mw]);
157
+ }
158
+
159
+ function iou(a, b) {
160
+ const x1 = Math.max(a[0], b[0]), y1 = Math.max(a[1], b[1]);
161
+ const x2 = Math.min(a[2], b[2]), y2 = Math.min(a[3], b[3]);
162
+ const inter = Math.max(0, x2 - x1) * Math.max(0, y2 - y1);
163
+ const aa = (a[2]-a[0])*(a[3]-a[1]), bb = (b[2]-b[0])*(b[3]-b[1]);
164
+ return inter / Math.max(aa + bb - inter, 1e-9);
165
+ }
166
+
167
+ function nms(boxes, scores, thr) {
168
+ const idx = scores.map((s, i) => i).sort((a, b) => scores[b] - scores[a]);
169
+ const keep = [];
170
+ const used = new Array(boxes.length).fill(false);
171
+ for (const i of idx) {
172
+ if (used[i]) continue;
173
+ keep.push(i);
174
+ for (const j of idx) {
175
+ if (!used[j] && j !== i && iou(boxes[i], boxes[j]) > thr) used[j] = true;
176
+ }
177
+ }
178
+ return keep;
179
+ }
180
+
181
+ function decode(out, nc) {
182
+ const dims = out.dims; // [1, C, N] 或 [1, N, C]
183
+ const C = dims[1], N = dims[2];
184
+ const data = out.data;
185
+ const get = (c, n) => data[c * N + n];
186
+ if (C !== 4 + nc) throw new Error(`输出通道 ${C} 与类别数 ${nc} 不匹配`);
187
+ const boxes = [], scores = [], cls = [];
188
+ for (let n = 0; n < N; n++) {
189
+ let best = 0, bi = 0;
190
+ for (let c = 0; c < nc; c++) {
191
+ const s = get(4 + c, n);
192
+ if (s > best) { best = s; bi = c; }
193
+ }
194
+ const cx = get(0, n), cy = get(1, n), w = get(2, n), h = get(3, n);
195
+ boxes.push([cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2]);
196
+ scores.push(best); cls.push(bi);
197
+ }
198
+ return { boxes, scores, cls };
199
+ }
200
+
201
+ async function detect() {
202
+ if (!img) return;
203
+ const key = $("model").value;
204
+ const token = $("token").value.trim();
205
+ const conf = parseFloat($("conf").value), iouThr = parseFloat($("iou").value);
206
+ const t0 = performance.now();
207
+ try {
208
+ const { sess, inputName, mw, mh } = await getSession(key, token);
209
+ const lb = letterboxTo([mw, mh]);
210
+ const feeds = {}; feeds[inputName] = toTensor(lb.canvas, mw, mh);
211
+ const out = (await sess.run(feeds))[sess.outputNames[0]];
212
+ const labels = MODELS[key].labels;
213
+ const { boxes, scores, cls } = decode(out, labels.length);
214
+
215
+ const picked = [];
216
+ for (let c = 0; c < labels.length; c++) {
217
+ const idx = [];
218
+ for (let i = 0; i < scores.length; i++) if (cls[i] === c && scores[i] >= conf) idx.push(i);
219
+ if (!idx.length) continue;
220
+ const b = idx.map(i => boxes[i]), s = idx.map(i => scores[i]);
221
+ for (const k of nms(b, s, iouThr)) picked.push({ box: b[k], score: s[k], cls: c });
222
+ }
223
+ picked.sort((a, b) => b.score - a.score);
224
+
225
+ drawBase();
226
+ const tb = $("tbl").querySelector("tbody");
227
+ tb.innerHTML = "";
228
+ picked.slice(0, 30).forEach(({ box, score, cls: c }) => {
229
+ const x1 = (box[0] - lb.left) / lb.r, y1 = (box[1] - lb.top) / lb.r;
230
+ const x2 = (box[2] - lb.left) / lb.r, y2 = (box[3] - lb.top) / lb.r;
231
+ const name = labels[c];
232
+ const color = COLORS[name] || "#fff";
233
+ ctx.strokeStyle = color; ctx.lineWidth = 2;
234
+ ctx.strokeRect(x1, y1, x2 - x1, y2 - y1);
235
+ ctx.fillStyle = color;
236
+ ctx.font = "12px Consolas,monospace";
237
+ ctx.fillText(`${ZH[name] || name} ${score.toFixed(2)}`, x1 + 2, Math.max(11, y1 - 4));
238
+ const tr = document.createElement("tr");
239
+ tr.innerHTML = `<td>${ZH[name] || name}</td><td>${score.toFixed(3)}</td>
240
+ <td>${[x1,y1,x2,y2].map(v => v.toFixed(1)).join(", ")}</td><td>${(y2 - y1).toFixed(1)}</td>`;
241
+ tb.appendChild(tr);
242
+ });
243
+ const ms = (performance.now() - t0).toFixed(0);
244
+ log(`检出 ${picked.length} 个框 · 整段 ${ms} ms(含首次建会话时会更久)`);
245
+ } catch (e) {
246
+ log("出错了:" + e.message);
247
+ }
248
+ }
249
+
250
+ function loadImage(src) {
251
+ return new Promise((ok, bad) => {
252
+ const im = new Image();
253
+ im.crossOrigin = "anonymous";
254
+ im.onload = () => { img = im; drawBase(); ok(); };
255
+ im.onerror = bad;
256
+ im.src = src;
257
+ });
258
+ }
259
+
260
+ $("file").addEventListener("change", async (ev) => {
261
+ const f = ev.target.files[0];
262
+ if (!f) return;
263
+ const url = URL.createObjectURL(f);
264
+ await loadImage(url);
265
+ detect();
266
+ });
267
+ $("ex1").onclick = async () => { await loadImage("examples/sample01.png"); detect(); };
268
+ $("ex2").onclick = async () => { await loadImage("examples/sample02.png"); detect(); };
269
+ $("conf").oninput = () => { $("cfv").textContent = $("conf").value; };
270
+ $("iou").oninput = () => { $("iouv").textContent = $("iou").value; };
271
+ $("run").onclick = detect;
272
+ $("model").addEventListener("change", async () => {
273
+ const key = $("model").value;
274
+ if (MODELS[key].gated && !$("token").value.trim()) {
275
+ log("这个模型是 gated:把 HF token 填进去再点检测。");
276
+ } else {
277
+ log("模型已切换,点「检测」重跑。");
278
+ }
279
+ });
280
+
281
+ (async () => {
282
+ try {
283
+ await getSession("local", "");
284
+ $("run").disabled = false;
285
+ log("模型就绪。选一张图或点示例。");
286
+ await loadImage("examples/sample01.png");
287
+ detect();
288
+ } catch (e) {
289
+ log("初始化失败:" + e.message + "\n(如果是 CDN 被挡,onnnxruntime-web 的 js 加载不出来)");
290
+ }
291
+ })();
292
+ </script>
293
+ </body>
294
  </html>
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio>=4.44
2
+ onnxruntime>=1.16
3
+ numpy>=1.24
4
+ pillow>=10.0
5
+ huggingface_hub>=0.24