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

如何在Label Studio JS部署中自动添加OCR预测至标注区域

实现Label Studio创建Bounding Box时自动调用OCR并填充Transcription

1. 监听区域创建事件

Label Studio编辑器实例内置了regioncreated事件,这就是你需要的新区域创建钩子。用户创建完bounding-box后,这个事件会立即触发,可在回调里处理后续逻辑:

// 假设你的Label Studio实例变量为ls
ls.on('regioncreated', (event) => {
  const region = event.detail.region;
  // 只处理矩形(bounding-box)类型的区域
  if (region.type === 'rectangle') {
    handleOCRForRegion(region);
  }
});

2. 提取区域与图片信息

要调用OCR API,需获取bounding-box的坐标参数和当前标注图片的信息。从region对象中可直接读取相对坐标,再转换为图片的绝对像素值:

function handleOCRForRegion(region) {
  // 获取区域相对坐标(百分比)
  const { x, y, width, height } = region.value;
  // 获取当前标注的图片元素
  const imageElement = ls.getRootElement().querySelector('.ls-image-container img');
  const imgWidth = imageElement.naturalWidth;
  const imgHeight = imageElement.naturalHeight;
  
  // 转换为绝对像素坐标
  const absoluteX = (x / 100) * imgWidth;
  const absoluteY = (y / 100) * imgHeight;
  const absoluteWidth = (width / 100) * imgWidth;
  const absoluteHeight = (height / 100) * imgHeight;
  
  // 截取区域图片(用于OCR识别)
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  canvas.width = absoluteWidth;
  canvas.height = absoluteHeight;
  ctx.drawImage(imageElement, absoluteX, absoluteY, absoluteWidth, absoluteHeight, 0, 0, absoluteWidth, absoluteHeight);
  const imageDataURL = canvas.toDataURL('image/png');
  
  // 调用OCR API并更新transcription
  callOCRAPI(imageDataURL).then(ocrText => {
    updateRegionTranscription(region, ocrText);
  });
}

3. 调用外部OCR API

替换以下示例代码为你的实际OCR服务(如Google OCR)请求逻辑,注意处理认证和跨域问题:

async function callOCRAPI(imageData) {
  const response = await fetch('https://your-ocr-api-endpoint', {
    method: 'POST',
    body: JSON.stringify({
      image: imageData,
      // 补充OCR API所需的其他参数
    }),
    headers: {
      'Content-Type': 'application/json',
      // 添加API认证头,比如Authorization: 'Bearer YOUR_KEY'
    }
  });
  const result = await response.json();
  // 根据API返回格式提取文本内容
  return result.ocr_text || '';
}

4. 更新区域的Transcription

拿到OCR结果后,直接修改region对象的value属性,再调用update()方法同步到Label Studio界面和标注数据:

function updateRegionTranscription(region, text) {
  // 给区域添加transcription字段
  region.value.transcription = text;
  // 触发Label Studio界面更新
  region.update();
  
  // 如需自动保存标注,可调用:
  // ls.submitAnnotation();
}

关键注意事项

  • 确保Label Studio实例已正确初始化,变量ls指向你的编辑器实例。
  • 不同版本的Label Studio可能在事件名或region对象结构上有细微差异,可查看对应版本官方文档的Editor Events和Region API章节。
  • OCR API若存在跨域问题,需通过后端代理请求或配置API的CORS规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 02:05:07