Vue3 使用OCR识别图片文字

Tesseract.js 是一个javascript库,可以从图像中获取几乎任何语言的单词,支持文本转pdf功能,精准度很高。

1. 安装

npm install tesseract.js

2. 示例代码(vue3版) 

<template>
  <div class="container">
    <div class="l_box">
      <el-image class="c_img" :src="url" fit="contain" />
      <div class="btn_box">
        <el-button type="primary" @click="getImgText" style="margin-right: 10px;" :disabled="loading">解 析</el-button>
        <el-upload class="upload-demo" :limit="1" :on-change="handleChange" accept=".jpg, .jpeg, .png, .bmp"
          :show-file-list="false" :auto-upload="false">
          <el-button type="primary" :disabled="loading">上 传</el-button>
        </el-upload>
        <el-button type="primary" @click="download" style="margin-left: 10px;" :disabled="loading">下载PDF</el-button>
      </div>
    </div>
    <pre class="c_value" v-loading="loading">{{ word }}</pre>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { createWorker } from 'tesseract.js';

let url = ref('https://tesseract.projectnaptha.com/img/eng_bw.png')
let word = ref('')
let loading = ref(false)
let worker = ref(null)
let pdf = ref(null)

onMounted(() => {
  init()
})

onUnmounted(() => {
  // 卸载插件  
  worker.value.terminate()
})

const init = async () => {
  // 初始化插件  
  worker.value = await createWorker(['eng', 'chi_sim'], 1, {
    logger: m => console.log(m),
  });
}

// 获取图片链接文本
const getImgText = async () => {
  loading.value = true
  try {
    const { data } = await worker.value.recognize(url.value, { pdfTitle: 'Example PDF' }, { pdf: true });
    pdf.value = data.pdf
    word.value = data.text
    loading.value = false
  } catch (error) {
    loading.value = false
    ElMessage({
      message: '解析失败',
      type: 'warning',
    })
  }
}

// 上传附件解析
const handleChange = async (file) => {
  url.value = URL.createObjectURL(file.raw)
  getImgText()
}


// 下载PDF
const download = () => {
  const blob = new Blob([new Uint8Array(pdf.value)], { type: 'application/pdf' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = 'example.pdf';
  link.click();
  URL.revokeObjectURL(url);
}

</script>
<style scoped lang="scss">
.container {
  width: 100%;
  height: 100%;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;

  .l_box {
    width: 48%;
    height: 100%;
    margin-right: 2%;

    .c_img {
      width: 100%;
      height: calc(100% - 40px);
    }

    .btn_box {
      height: 50px;
      display: flex;
      align-items: center;
    }
  }

  .c_value {
    width: 50%;
    min-height: 500px;
    border: 1px solid #999;
    line-height: 30px;
    padding: 20px;
  }
}
</style>
效果图

更多api可以去官网尝试了 tesseract.projectnaptha.com 。 

### 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 &#39;tesseract.js&#39;; export default { data() { return { imageSrc: null, ocrResult: &#39;&#39;, error: &#39;&#39; }; }, 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, &#39;chi_sim&#39;, // 中文简体 { 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, &#39;wordsWithBoundingBoxes&#39;, 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、付费专栏及课程。

余额充值