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>
页面: