paddleJs-OCR + vue3 + TS

本文介绍了如何在Vue3应用中使用PaddleJS的OCR模型进行图像识别,并展示了TypeScript编写的组件和安装过程。开发者可以跟随教程实现一个简单的上传图片并识别文字的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

paddleJs-OCR + vue3 + TS DEMO

npm install @paddlejs-models/ocr@1.2.3

 


 

App.vue

<script setup lang="ts">
import OCR from './components/OCR.vue'
</script>

<template>
  <OCR />
</template>

<style scoped>
.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}
.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}
</style>

 OCR.vue

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import * as ocr from "@paddlejs-models/ocr";

const canvasRef = ref<InstanceType<typeof Element>>();
const inputRef = ref<InstanceType<typeof Element>>();
const imageRef = ref<InstanceType<typeof Image>>();

const state = reactive({
  imageSrc: "",
  lodingText: "加载中....",
  style: {
    display: "block",
  },
  ocrTexts: [] as string[],
});

onMounted(() => {
  console.log("开始初始化...");
  ocr.init().then(() => {
    console.log("初始化完成");
    state.style.display = "none";
  });
});

function handleChange(e: Event) {
  console.log(e);
  if (
    e == null ||
    e.target == null ||
    (e!.target as HTMLInputElement).files!.length == 0
  ) {
    return;
  }

  state.style.display = "block";
  state.lodingText = "识别中....";

  state.imageSrc = URL.createObjectURL((e.target as any).files[0]);
  if (imageRef.value) {
    console.log(imageRef,'imageRef');
    
    imageRef.value.onload = async function () {
      const res = await ocr.recognize(imageRef.value);
      state.ocrTexts = res.text;
      state.style.display = "none";
    };
  }
}
</script>

<template>
  <div style="border: solid 1px #ccc">
    <div class="m15">
      <input
        type="file"
        accept="image/*"
        ref="inputRef"
        @change="handleChange"
      />
    </div>
    <div class="m15">
      <img ref="imageRef" :src="state.imageSrc" />
    </div>
    <div class="m15">
      <canvas id="canvas" ref="canvasRef"></canvas>
    </div>
    <div style="border: solid 1px #ccc">
      <h2>识别到的文字</h2>
      <p v-for="orcText in state.ocrTexts">{{ orcText }}</p>
    </div>

    <div class="isLoading" :style="state.style">
      <p class="loading-text center">{{ state.lodingText }}</p>
    </div>
  </div>
</template>

<style scoped>
.read-the-docs {
  color: #888;
}
.isLoading {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
}
.isLoading .loading-text {
  color: #fff;
  font-size: 24px;
  text-align: center;
  line-height: 100vh;
}
.m15 {
  margin: 15px;
}
</style>

页面:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值