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 packages2# Usage: pip install -r requirements.txt3
4# Flask Framework5flask6easyocr
Application Code
The application configures a Flask
app with the EasyOCR
library and a simple HTML form with a file upload:
app.py
1import os2from flask import Flask, flash, request, redirect, url_for, jsonify3from werkzeug.utils import secure_filename4import easyocr5
6reader = easyocr.Reader(['en'], True)7
8ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}9FILE_DIR = 'files'10
11app = Flask(__name__)12
13if not os.path.exists(FILE_DIR):14 os.makedirs(FILE_DIR)15
16def allowed_file(filename):17 return '.' in filename and \18 filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS19
20@app.route('/', methods=['GET', 'POST'])21def upload_file():22 if request.method == 'POST':23 # check if the post request has the file part24 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 also29 # submit an empty part without filename30 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 upload39 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)