【vue + JS】OCR图片识别、文字识别

一、需求说明

将上传图片中的文字内容识别出来
 

二、需求分析

利用“百度文字识别”功能,将上传的图片转成base64格式,调取对应的识别接口获取图片上的文字。


  1. 上传图片
  2. 将图片转换成base64格式
  3. 获取图片识别所需的token
  4. 执行OCR图片识别

三、解决方法

1、html:上传图片按钮

<a-upload
  accept=".png,.jpg"
  :beforeUpload="beforeUploadFile"
  @reject="message.warning('上传文件格式不正确')"
  :showUploadList="false"
>
  <a-button class="btn-bg">
    <svg-icon icon-class="upload" class="btn-icon"></svg-icon>
    上传照片识别
  </a-button>
</a-upload>

2、js:实现功能方法

// 环境变量配置
const API_KEY = "xxx";
const SECRET_KEY = "xxx";

const loading = ref(false);
const imageData = ref<string | ArrayBuffer | null>(null);
const result = ref(null);

/**
 * @description: 将上传的图片转换成base64格式
 * @param {object} file 文件
 * @return {*}
 */
const handleFileChange = (file: any) => {
  resultData.isLeft = false;
  let fr = new FileReader();
  fr.readAsDataURL(file); // 读取文件并返回DataURL
  fr.onload = function () {
    imageData.value = fr.result; // 获取Base64编码
  };
  setTimeout(() => {
    recognizeImage(); //识别图片
  }, 500);
};

/**
 * @description: 利用百度OCR识别api文档,进行图片识别
 * @return {*}
 */
const recognizeImage = async () => {
  if (!imageData.value) return;
  loading.value = true;
  try {
    const accessToken = await getAccessToken();
    const params = new URLSearchParams();
    params.append("image", imageData.value as string);
    params.append("detect_direction", "true"); // 自动旋转检测‌:ml-citation{ref="4" data="citationList"}
    const response = await axios.post("/baiduApi/rest/2.0/ocr/v1/accurate_basic", params, {
      params: { access_token: accessToken },
      headers: { "Content-Type": "application/x-www-form-urlencoded" }
    });
    // response.data.words_result 识别出的文字
    result.value = response.data.words_result as any;
  } catch (error) {
    handleError(error);// 错误处理
  } finally {
    loading.value = false;
  }
};

/**
 * @description: 错误处理
 * @return {*}
 */
const handleError = (error: any) => {
  if (error.response?.data?.error_code) {
    const errorCode = error.response.data.error_code;
    switch (errorCode) {
      case 18:
        alert("API调用频率超限");
        break;
      case 216202:
        alert("未检测到图片有效内容");
        break;
      default:
        alert(`识别失败,错误码:${errorCode}`);
    }
  }
};

/**
 * @description: 获取图片识别所需的token
 * @return {*}
 */
const getAccessToken = async () => {
  try {
    const response = await axios.post("/baiduApi/oauth/2.0/token", null, {
      params: {
        grant_type: "client_credentials",
        client_id: API_KEY,
        client_secret: SECRET_KEY
      }
    });
    return response.data.access_token;
  } catch (error) {
    console.error("获取Token失败:", error);
    throw error;
  }
};

 PS:注意跨域问题

vite.config.ts 文件中设置代理

server: {
  host: "0.0.0.0",
  port: 4000, // 设置服务启动端口号
  open: false, // 设置服务启动时是否自动打开浏览器
  cors: true, // 允许跨域
  hmr: true,

  // 设置代理,根据我们项目实际情况配置
  proxy: {
    "/baiduApi": {
      target: "https://aip.baidubce.com",
      changeOrigin: true,
      secure: false, // 关闭SSL证书验证‌:ml-citation{ref="3,4" data="citationList"}
      rejectUnauthorized: false, // 允许自签名证书‌:ml-citation{ref="3,4" data="citationList"}
      rewrite: path => path.replace(/^\/baiduApi/, "")
    }
  }
}


四、参考链接

百度文档:文字识别OCR

### Vue 实现 OCR 文字识别并获取文字坐标 为了在 Vue 项目中实现 OCR 文字识别并获取文字坐标,可以利用 Tesseract OCR 库来处理图像中的文本提取,并结合其他工具或自定义逻辑来解析返回的结果以获得每个单词的位置数据。 #### 安装依赖库 首先,在 Vue 项目的命令行环境中安装 `tesseract.js`: ```bash npm install tesseract.js --save ``` #### 创建 OCR 组件 创建一个新的组件文件 `OcrComponent.vue` 来封装 OCR 功能。此组件负责接收图片输入、调用 Tesseract 进行 OCR 处理以及展示结果。 ```vue <template> <div class="ocr-component"> <!-- 图片上传 --> <input type="file" @change="onFileChange"/> <!-- 显示原始图片 --> <img :src="imageSrc" alt="Uploaded Image"/> <!-- 展示 OCR 结果 --> <pre>{{ ocrResult }}</pre> <!-- 错误提示 --> <p v-if="error">{{ error }}</p> </div> </template> <script> import Tesseract from 'tesseract.js'; export default { data() { return { imageSrc: null, ocrResult: '', error: '' }; }, methods: { onFileChange(event) { const file = event.target.files[0]; if (!file || !/^image\//.test(file.type)) { this.error = "请选择有效的图片文件"; return; } let reader = new FileReader(); reader.onloadend = () => { this.imageSrc = reader.result; // 使用 Tesseract 对图片进行 OCR 并获取带坐标的文本信息 Tesseract.recognize( this.imageSrc, 'chi_sim', // 中文简体 { logger(m) { console.log(m); } } ).then(({data})=>{ this.ocrResult = JSON.stringify(data.text, undefined, 2); // 解析得到的文字及其位置信息 const wordsWithBoundingBoxes = data.blocks.flatMap(block => block.lines.flatMap(line => line.words.map(word => ({ text: word.text, boundingBox: [ [word.boundingBox.leftTop.x, word.boundingBox.leftTop.y], [word.boundingBox.rightTop.x, word.boundingBox.rightTop.y], [word.boundingBox.rightBottom.x, word.boundingBox.rightBottom.y], [word.boundingBox.leftBottom.x, word.boundingBox.leftBottom.y] ] }))) ); console.table(wordsWithBoundingBoxes); // 将带有边框的信息保存到实例属性以便后续操作 this.$set(this, 'wordsWithBoundingBoxes', wordsWithBoundingBoxes); }).catch(err=>this.error=err.message); }; try{ reader.readAsDataURL(file); } catch (e){ this.error=e.toString(); } } } }; </script> ``` 上述代码展示了如何在一个简单的 Vue 单页应用中集成 Tesseract OCR 技术来进行基本的 OCR 操作[^1]。当用户选择了要分析的图片之后,程序会读取该图片并通过 Tesseract 提取出其中所含有的文本内容连同它们各自的边界框(即坐标)一起显示出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值