首页
/ 前端AI物体计数:5分钟实现图像中物体数量统计

前端AI物体计数:5分钟实现图像中物体数量统计

2026-02-05 04:35:29作者:廉彬冶Miranda

你是否还在为电商商品库存盘点、工业零件计数等重复劳动烦恼?本文将基于gh_mirrors/fr/frontend-stuff项目提供的前端工具链,教你如何使用浏览器端AI技术实现图像中物体的自动计数。读完本文你将获得:

  • 无需后端服务器的纯前端物体计数方案
  • 基于TensorFlow.js的图像识别模型集成方法
  • 完整的前端实现代码与项目结构解析

技术选型与项目资源

本方案主要依赖项目中收录的两个核心库:

技术库 用途 项目文档
TensorFlow.js 浏览器端机器学习框架 项目README中"Neural Networks"分类
canvas-sketch 图像处理与可视化工具 项目README中"Canvas and SVG"分类

通过分析package.json可知,项目已集成@tensorflow/tfjs和tfjs-models/coco-ssd作为图像识别基础,无需额外安装依赖。

实现步骤

1. 环境准备

首先克隆项目仓库并安装依赖:

git clone https://gitcode.com/gh_mirrors/fr/frontend-stuff.git
cd frontend-stuff
npm install

2. 核心代码实现

创建src/object-counter.js文件,实现物体检测与计数功能:

import * as tf from '@tensorflow/tfjs';
import * as cocossd from '@tensorflow-models/coco-ssd';
import { createCanvas } from 'canvas-sketch';

class ObjectCounter {
  constructor() {
    this.model = null;
    this.canvas = null;
    this.ctx = null;
  }

  // 初始化模型
  async initModel() {
    this.model = await cocossd.load();
    console.log('模型加载完成');
  }

  // 创建画布
  setupCanvas(imageElement) {
    const canvas = createCanvas(imageElement.width, imageElement.height);
    this.ctx = canvas.getContext('2d');
    this.ctx.drawImage(imageElement, 0, 0);
    return canvas;
  }

  // 检测并计数物体
  async detectAndCount(imageElement) {
    if (!this.model) await this.initModel();
    
    this.canvas = this.setupCanvas(imageElement);
    const predictions = await this.model.detect(this.canvas);
    
    // 绘制检测结果
    this.drawPredictions(predictions);
    
    // 统计各类物体数量
    const counts = this.countObjects(predictions);
    return counts;
  }

  // 绘制检测框和标签
  drawPredictions(predictions) {
    predictions.forEach(prediction => {
      this.ctx.strokeStyle = '#FF0000';
      this.ctx.lineWidth = 2;
      this.ctx.strokeRect(
        prediction.bbox[0], 
        prediction.bbox[1], 
        prediction.bbox[2], 
        prediction.bbox[3]
      );
      
      this.ctx.fillStyle = '#FF0000';
      this.ctx.fillText(
        `${prediction.class}: ${prediction.score.toFixed(2)}`,
        prediction.bbox[0], 
        prediction.bbox[1] - 5
      );
    });
  }

  // 计数不同类别的物体
  countObjects(predictions) {
    const counts = {};
    predictions.forEach(prediction => {
      const label = prediction.class;
      counts[label] = (counts[label] || 0) + 1;
    });
    return counts;
  }
}

// 导出实例
export const objectCounter = new ObjectCounter();

3. 前端界面集成

创建public/index.html文件,实现用户交互界面:

<!DOCTYPE html>
<html>
<head>
  <title>前端AI物体计数工具</title>
  <style>
    .container {
      max-width: 800px;
      margin: 0 auto;
      padding: 20px;
    }
    #imageInput {
      margin: 20px 0;
    }
    #result {
      margin-top: 20px;
      padding: 10px;
      border: 1px solid #ccc;
    }
    #canvasContainer {
      margin-top: 20px;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>AI物体计数工具</h1>
    <input type="file" id="imageInput" accept="image/*">
    <div id="canvasContainer"></div>
    <div id="result"></div>
  </div>

  <script type="module">
    import { objectCounter } from '../src/object-counter.js';

    const imageInput = document.getElementById('imageInput');
    const canvasContainer = document.getElementById('canvasContainer');
    const resultElement = document.getElementById('result');

    imageInput.addEventListener('change', async (e) => {
      const file = e.target.files[0];
      if (!file) return;

      // 显示上传的图片
      const imageElement = new Image();
      imageElement.src = URL.createObjectURL(file);
      
      imageElement.onload = async () => {
        // 检测并计数物体
        const counts = await objectCounter.detectAndCount(imageElement);
        
        // 显示结果
        canvasContainer.appendChild(objectCounter.canvas);
        
        // 格式化计数结果
        let resultHTML = '<h3>计数结果:</h3><ul>';
        for (const [label, count] of Object.entries(counts)) {
          resultHTML += `<li>${label}: ${count}个</li>`;
        }
        resultHTML += '</ul>';
        resultElement.innerHTML = resultHTML;
      };
    });
  </script>
</body>
</html>

4. 运行与测试

启动开发服务器:

npm run dev

在浏览器中访问http://localhost:8080,上传包含多个物体的图片即可看到计数结果。

优化与扩展

性能优化

  1. 使用WebWorker进行模型推理,避免阻塞UI线程:
// worker.js
import * as tf from '@tensorflow/tfjs';
import * as cocossd from '@tensorflow-models/coco-ssd';

let model;

self.onmessage = async (e) => {
  if (e.data.type === 'INIT_MODEL') {
    model = await cocossd.load();
    self.postMessage({ type: 'MODEL_READY' });
  } else if (e.data.type === 'DETECT_OBJECTS') {
    const predictions = await model.detect(e.data.imageData);
    self.postMessage({ type: 'DETECTION_RESULT', predictions });
  }
};
  1. 模型选择与量化:
// 加载量化模型,减小体积提升速度
model = await cocossd.load({
  modelUrl: 'https://storage.googleapis.com/tfjs-models/tfjs/coco-ssd/mobilenet_v1/model.json',
  base: 'mobilenet_v1',
  modelSize: 'small'
});

功能扩展

可结合项目中的chart.js实现计数结果可视化,或使用fabric.js添加交互式标注功能。

总结

本文基于gh_mirrors/fr/frontend-stuff项目实现了一个纯前端的AI物体计数工具,利用TensorFlow.js在浏览器中直接运行物体检测模型,无需后端支持。通过这种方案,开发者可以快速构建出商品盘点、零件计数等实用工具,大大提高工作效率。

完整代码与更多示例可在项目的examples/object-counter目录下找到。如需深入学习,建议参考项目文档中的jscodeshift-tutorial和TensorFlow.js官方文档。

登录后查看全文
热门项目推荐
相关项目推荐