Implement OCR with React#2
honorezemagho
Posted on October 16, 2020
In the last tutorial we have implemented the upload functionality.
In this tutorial we are going to add Tesseract.js.
This article is divided in two parts. This is the part 2 , for the Part1 click here
Requirements
- Nodejs version 8.10 or Higher.
First, we are going to install Tesseract.js package
npm install tesseract.js
After we are going to import createWorker function it in src/App.js
file .
import {createWorker} from "tesseract.js";
inside the function App() we are going to add a worker and a method to recognize text inside an image.
const worker = createWorker({
logger: (m) => console.log(m),
});
const ExtractTextFromImage = async (imageUrl) => {
await worker.load();
await worker.loadLanguage("eng");
await worker.initialize("eng");
const {
data: {
text
},
} = await worker.recognize(imageUrl);
setText(text);
await worker.terminate();
};
After we are going to define the state for image URL and text display. we are going to use useState and useEffect React Hook. First of all, we need to import useState from react.
import React,{useEffect,useState} from "react";
After
const [ text, setText] = useState(null);
const [imageUrl] = useState(null);
useEffect(() => {
if (imageUrl != null) {
ExtractTextFromImage();
}
});
Now we are going to add a container to display the text from the image in React.Fragment bloc.
<div className = "container text-center pt-5" >
{text}
</div>
and update the text when processing the image.
const handleChangeStatus = ({
meta
}, status) => {
if (status === 'headers_received') {
alert("Uploaded");
setText("Recognizing...");
ExtractTextFromImage(meta.url);
} else if (status === 'aborted') {
alert("Something went wrong")
}
}
For the GitHub repository click Here
This article is divided into two parts. This is the part 2 , for the Part1 click here
Posted on October 16, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.