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
| <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>YOLO 纯前端实时目标检测 - ONNX Runtime Web</title> <script src="https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js"></script> <style> body { margin: 0; padding: 0; background-color: #0f0f13; color: #ffffff; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 100vh; } h1 { margin: 10px 0; font-size: 1.8rem; text-shadow: 0 0 10px rgba(0, 255, 200, 0.5); } .container { position: relative; width: 640px; height: 480px; border-radius: 12px; overflow: hidden; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.7); border: 2px solid #333344; } #webcam { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; transform: scaleX(-1); } #canvas { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 10; transform: scaleX(-1); } .controls { margin-top: 15px; display: flex; gap: 15px; align-items: center; } button { padding: 10px 20px; background: linear-gradient(135deg, #00f2fe 0%, #4facfe 100%); border: none; border-radius: 6px; color: white; font-weight: bold; cursor: pointer; transition: all 0.3s ease; box-shadow: 0 4px 15px rgba(0, 242, 254, 0.4); } button:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0, 242, 254, 0.6); } #status { font-size: 0.9rem; color: #aaaaaa; } #fps-display { font-size: 1rem; color: #00ffc8; font-weight: bold; } </style> </head> <body>
<h1>YOLO 纯前端实时目标检测</h1> <div id="status">正在初始化环境并加载模型,请稍候...</div> <div id="fps-display">FPS: -- | 延迟: -- ms</div>
<br> <div class="container"> <video id="webcam" autoplay playsinline muted></video> <canvas id="canvas" width="640" height="480"></canvas> </div>
<div class="controls"> <button id="start-btn" disabled>开启摄像头检测</button> </div>
<script> const CLASS_NAMES = [ "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch", "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush" ];
let session = null; let webcamElement = document.getElementById("webcam"); let canvasElement = document.getElementById("canvas"); let ctx = canvasElement.getContext("2d"); let statusElement = document.getElementById("status"); let fpsElement = document.getElementById("fps-display"); let startBtn = document.getElementById("start-btn"); let isRunning = false;
async function initApp() { try { const options = { executionProviders: ['webgl', 'wasm'], }; statusElement.innerText = "正在从网络下载 YOLO ONNX 模型并配置渲染器 (约 12MB)..."; session = await ort.InferenceSession.create("./yolo11n.onnx", options); statusElement.innerText = "模型加载成功!"; startBtn.disabled = false; } catch (err) { statusElement.innerText = "模型加载失败,请确保 yolo11n.onnx 放置在 HTML 同级目录下且配置了本地静态服务器。"; console.error(err); } }
function preprocess(videoFrame, modelWidth, modelHeight) { const canvas = document.createElement("canvas"); canvas.width = modelWidth; canvas.height = modelHeight; const ctx = canvas.getContext("2d"); ctx.drawImage(videoFrame, 0, 0, modelWidth, modelHeight); const imgData = ctx.getImageData(0, 0, modelWidth, modelHeight); const data = imgData.data; const float32Array = new Float32Array(3 * modelWidth * modelHeight); for (let i = 0; i < modelWidth * modelHeight; i++) { float32Array[i] = data[i * 4] / 255.0; float32Array[i + modelWidth * modelHeight] = data[i * 4 + 1] / 255.0; float32Array[i + 2 * modelWidth * modelHeight] = data[i * 4 + 2] / 255.0; } return new ort.Tensor("float32", float32Array, [1, 3, modelWidth, modelHeight]); }
let lastFrameTime = performance.now(); async function detectFrame() { if (!isRunning) return;
const startTime = performance.now();
const inputTensor = preprocess(webcamElement, 640, 640);
const feeds = { [session.inputNames[0]]: inputTensor }; const results = await session.run(feeds); const output = results[session.outputNames[0]];
const boxes = postprocess(output.data, 0.45, 0.45);
drawDetections(boxes);
const endTime = performance.now(); const latency = Math.round(endTime - startTime); const fps = Math.round(1000 / (endTime - lastFrameTime)); lastFrameTime = endTime; fpsElement.innerText = `FPS: ${fps} | 推理延迟: ${latency} ms`;
requestAnimationFrame(detectFrame); }
function postprocess(outputData, confThreshold, iouThreshold) { const boxes = []; const numClasses = 80; const numCandidates = 8400;
for (let c = 0; c < numCandidates; c++) { let maxScore = 0; let classId = -1; for (let i = 0; i < numClasses; i++) { const score = outputData[(4 + i) * numCandidates + c]; if (score > maxScore) { maxScore = score; classId = i; } }
if (maxScore > confThreshold) { const cx = outputData[0 * numCandidates + c]; const cy = outputData[1 * numCandidates + c]; const w = outputData[2 * numCandidates + c]; const h = outputData[3 * numCandidates + c];
const x1 = (cx - w / 2); const y1 = (cy - h / 2); boxes.push({ box: [x1, y1, w, h], score: maxScore, classId: classId }); } }
return nms(boxes, iouThreshold); }
function nms(boxes, iouThreshold) { boxes.sort((a, b) => b.score - a.score); const result = []; while (boxes.length > 0) { const current = boxes.shift(); result.push(current); boxes = boxes.filter(box => { const iou = calculateIoU(current.box, box.box); return iou < iouThreshold; }); } return result; }
function calculateIoU(box1, box2) { const [x1, y1, w1, h1] = box1; const [x2, y2, w2, h2] = box2; const area1 = w1 * h1; const area2 = w2 * h2; const interX1 = Math.max(x1, x2); const interY1 = Math.max(y1, y2); const interX2 = Math.min(x1 + w1, x2 + w2); const interY2 = Math.min(y1 + h1, y2 + h2); const interW = Math.max(0, interX2 - interX1); const interH = Math.max(0, interY2 - interY1); const interArea = interW * interH; const unionArea = area1 + area2 - interArea; return unionArea === 0 ? 0 : interArea / unionArea; }
function drawDetections(boxes) { ctx.clearRect(0, 0, canvasElement.width, canvasElement.height);
boxes.forEach(det => { const [x, y, w, h] = det.box; const score = det.score; const className = CLASS_NAMES[det.classId];
const scaleX = canvasElement.width / 640; const scaleY = canvasElement.height / 640; const drawX = x * scaleX; const drawY = y * scaleY; const drawW = w * scaleX; const drawH = h * scaleY;
ctx.strokeStyle = "#00ffc8"; ctx.lineWidth = 3; ctx.shadowBlur = 10; ctx.shadowColor = "#00ffc8"; ctx.strokeRect(drawX, drawY, drawW, drawH); ctx.shadowBlur = 0; ctx.fillStyle = "rgba(0, 255, 200, 0.85)"; const labelText = `${className} (${(score * 100).toFixed(0)}%)`; ctx.font = "bold 14px Arial"; const textWidth = ctx.measureText(labelText).width; ctx.fillRect(drawX, drawY - 24, textWidth + 12, 24);
ctx.fillStyle = "#000000"; ctx.fillText(labelText, drawX + 6, drawY - 7); }); }
async function startCamera() { try { const stream = await navigator.mediaDevices.getUserMedia({ video: { width: 640, height: 480, facingMode: "user" }, audio: false }); webcamElement.srcObject = stream; webcamElement.onloadedmetadata = () => { isRunning = true; detectFrame(); }; startBtn.innerText = "正在检测中..."; startBtn.disabled = true; } catch (err) { alert("摄像头获取失败,请确保当前网页以 localhost 或 HTTPS 方式访问并已授予摄像头访问权限。"); console.error(err); } }
startBtn.addEventListener("click", startCamera); window.onload = initApp; </script> </body> </html>
|