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

如何使用Node.js版Google Cloud Vision API客户端实现多类型检测

一次调用完成多种Google Vision检测的方法

当然可以!你完全不用分开调用client.labelDetection()、client.safeSearchDetection()这类单一检测接口——Google Vision API的Node.js客户端提供了更高效的批量检测方式:client.annotate()方法,能一次性提交多种检测请求,一次拿到所有结果。

核心实现思路

通过构建包含多个features的请求对象,指定你需要的所有检测类型,再传给annotate()方法即可。这样既减少了网络请求次数,也能统一处理返回结果。

代码示例:同时做标签检测和安全搜索检测

const vision = require('@google-cloud/vision');
const client = new vision.ImageAnnotatorClient();

async function detectMultipleFeatures() {
  // 构建请求:指定图片源和需要的检测类型
  const request = {
    image: {
      source: { imageUri: '你的图片URL地址' }
    },
    features: [
      { type: 'LABEL_DETECTION' }, // 标签检测
      { type: 'SAFE_SEARCH_DETECTION' }, // 安全搜索检测
      // 还可以添加其他检测类型,比如 FACE_DETECTION、TEXT_DETECTION 等
    ]
  };

  // 发送批量检测请求
  const [response] = await client.annotate(request);

  // 提取并处理不同检测的结果
  const labelResults = response.labelAnnotations;
  const safeSearchResults = response.safeSearchAnnotation;

  console.log('=== 标签检测结果 ===');
  labelResults.forEach(label => {
    console.log(`标签:${label.description},置信度:${label.score}`);
  });

  console.log('\n=== 安全搜索检测结果 ===');
  console.log(`成人内容等级:${safeSearchResults.adult}`);
  console.log(`暴力内容等级:${safeSearchResults.violence}`);
  console.log(`露骨内容等级:${safeSearchResults.racy}`);
}

// 执行函数并捕获错误
detectMultipleFeatures().catch(err => {
  console.error('检测出错:', err);
});

扩展:批量处理多张图片

如果需要同时处理多张图片,还可以传入请求数组,每张图片可以指定不同的检测类型:

async function batchDetectImages() {
  const requests = [
    {
      image: { source: { imageUri: '图片URL1' } },
      features: [{ type: 'LABEL_DETECTION' }, { type: 'SAFE_SEARCH_DETECTION' }]
    },
    {
      image: { source: { imageUri: '图片URL2' } },
      features: [{ type: 'TEXT_DETECTION' }] // 只做文字检测
    }
  ];

  const responses = await client.annotate(requests);
  
  // 遍历每张图片的结果
  responses.forEach((response, index) => {
    console.log(`\n=== 第${index+1}张图片检测结果 ===`);
    if (response.labelAnnotations) {
      console.log('标签:', response.labelAnnotations.map(l => l.description).join(', '));
    }
    if (response.textAnnotations) {
      console.log('识别到的文字:', response.textAnnotations[0].description);
    }
  });
}

常用检测类型参考

你可以根据需求在features数组中添加以下类型:

  • LABEL_DETECTION:图像标签检测
  • SAFE_SEARCH_DETECTION:安全搜索内容检测
  • FACE_DETECTION:人脸检测
  • TEXT_DETECTION:文字检测(OCR)
  • OBJECT_LOCALIZATION:物体定位
  • LOGO_DETECTION:Logo检测

内容的提问来源于stack exchange,提问作者Kaan Dönbekci

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:14:33