OCR with Python and EasyOCR

Create a basic application using EasyOCR and Flask that uses Machine Learning to Parse Text from an Image

Updated: 03 September 2023

A simple application to use EasyOCR and Flask to create a WebApp that is able to process images and return the relevant text

Requirements/Dependencies

The application has the following dependencies which should be in a requirements.txt file:

requirements.txt

1
# This file is used by pip to install required python packages
2
# Usage: pip install -r requirements.txt
3
4
# Flask Framework
5
flask
6
easyocr

Application Code

The application configures a Flask app with the EasyOCR library and a simple HTML form with a file upload:

app.py

1
import os
2
from flask import Flask, flash, request, redirect, url_for, jsonify
3
from werkzeug.utils import secure_filename
4
import easyocr
5
6
reader = easyocr.Reader(['en'], True)
7
8
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
9
FILE_DIR = 'files'
10
11
app = Flask(__name__)
12
13
if not os.path.exists(FILE_DIR):
14
os.makedirs(FILE_DIR)
15
16
def allowed_file(filename):
17
return '.' in filename and \
18
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
19
20
@app.route('/', methods=['GET', 'POST'])
21
def upload_file():
22
if request.method == 'POST':
23
# check if the post request has the file part
24
if 'file' not in request.files:
25
flash('No file part')
26
return redirect(request.url)
27
file = request.files['file']
28
# if user does not select file, browser also
29
# submit an empty part without filename
30
if file.filename == '':
31
flash('No selected file')
32
return redirect(request.url)
33
if file and allowed_file(file.filename):
34
filename = FILE_DIR + '/' + secure_filename(file.filename)
35
file.save(filename)
36
parsed = reader.readtext(filename)
37
text = '<br/>\n'.join(map(lambda x: x[1], parsed))
38
# handle file upload
39
return (text)
40
41
return '''
42
<!doctype html>
43
<title>Upload new File</title>
44
<h1>Upload new File</h1>
45
<form method=post enctype=multipart/form-data>
46
<input type=file name=file>
47
<input type=submit value=Upload>
48
</form>
49
'''

Run the Application

The application can be run with the flask run command from the application directory (the directory with the app.py file)