You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow图像识别代码优化需求:仅展示置信度最高的分类结果

Show Only the Top Confidence Prediction in TensorFlow.js

Alright, let's tweak your code so it only displays the prediction with the highest confidence instead of all results. Here's the adjusted version of your predict function:

async function predict() {
  // predict can take an image, video, or canvas HTML element
  const prediction = await model.predict(webcam.canvas);
  
  // Find the prediction with the highest confidence
  const topPrediction = prediction.reduce((highest, current) => {
    return current.probability > highest.probability ? current : highest;
  }, prediction[0]);
  
  // Format the result text
  const classPrediction = `${topPrediction.className}: ${topPrediction.probability.toFixed(2)}`;
  
  // Update the label container to only show the top result
  // Clear all old content first
  labelContainer.innerHTML = '';
  // Create a new element for the top result and add it to the container
  const resultDiv = document.createElement('div');
  resultDiv.textContent = classPrediction;
  labelContainer.appendChild(resultDiv);

  // Alternative: If your labelContainer has fixed pre-existing child nodes
  // labelContainer.childNodes.forEach(node => node.innerHTML = '');
  // labelContainer.childNodes[0].innerHTML = classPrediction;
}

Breakdown of the changes:

  • Finding the top prediction: We use the reduce method to loop through all predictions and keep track of the one with the highest probability value. This is a concise alternative to writing a manual for-loop, though either approach works.
  • Updating the UI: Instead of looping through all maxPredictions to update every child node, we clear the container first to remove old results, then add a new element with just the top prediction. If your HTML has a fixed set of result elements, you can use the commented alternative to only populate the first node and clear the rest.

This way, your camera feed will only show the most confident recognition result each time the predict function runs.

内容的提问来源于stack exchange,提问作者mmarchjr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 17:47:28