The Wayback Machine - https://web.archive.org/web/20240915091345/https://www.geeksforgeeks.org/optical-character-recognition-using-tensorflow/
Open In App

Optical Character Recognition using TensorFlow

Last Updated : 14 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Optical Character Recognition (OCR) stands as a transformative force, bridging the gap between the physical and digital worlds. OCR enables machines to interpret and convert printed or handwritten text into machine-readable data, revolutionizing how we interact with information. This article explores the powerful capabilities of OCR and presents a TensorFlow-based model, a testament to the evolution of deep learning in unlocking the potential of visual data.

What is Optical Character Recognition(OCR)?

Optical Character Recognition (OCR) is a technology that empowers computers to recognize and interpret text from images, whether scanned documents, photos, or handwritten notes. It has emerged as a vital component in various fields, from document digitization to aiding visually impaired individuals. The primary goal of OCR is to convert visual representations of characters into editable and searchable data, making it an invaluable tool in our increasingly digitized society. As we delve into the capabilities of OCR, we’ll showcase a practical implementation using TensorFlow, a popular open-source machine learning framework.

Optical Character Recognition(OCR) Implementation using TensorFlow

Before starting the implementation, let’s install TensorFlow using the following command:

!pip install tensorflow

TensorFlow is an open-source machine learning library developed by the Google Brain team. We will be using TensorFlow for implementing OCR as TensorFlow provides a flexible and extensive framework to build customized OCR models.

Importing Libraries

For the implementation, we will be using open cv, numpy, matplotlib, tensorflow, and keras.

Python3




import tensorflow as tf
from keras.models import Sequential
from keras.layers import Conv2D, Flatten, MaxPooling2D, Dense
import os
import cv2
import numpy as np


Loading dataset and Preprocessing

You can download the dataset from here and unzip the folder using following command:

!unzip /content/OCR_dataset.zip

Reading and Preprocessing Images:

  • files = os.path.join(dir, j) creates the full path to the current image file.
  • img = cv2.imread(files) reads the image using OpenCV.
  • img = cv2.resize(img, (64,64)) resizes the image to a fixed size (64×64 pixels).
  • img = np.array(img, dtype=np.float32) converts the image to a NumPy array with float32 data type.
  • img = img/255 normalizes the pixel values to the range [0, 1].

Building Lists of Images and Labels:

  • images.append(img) adds the preprocessed image to the list images.
  • labels.append(i) adds the corresponding label (class) to the list labels. The label is determined by the subdirectory name.

Python3




images = []
labels = []
 
path = '/content/data/training_data'
 
dir_list = os.listdir(path)
for i in dir_list:
  dir = os.path.join(path, i)
  file_list = os.listdir(dir)
  for j in file_list:
    files = os.path.join(dir, j)
    img = cv2.imread(files)
    img = cv2.resize(img, (64,64))
    img = np.array(img, dtype=np.float32)
    img = img/255
    images.append(img)
    labels.append(i)


Converting list to NumPy arrays:

  • ‘X’ is a NumPy array containing the preprocessed images. Each element of X is a 3D array representing an image.
  • ‘y’ is a NumPy array containing the corresponding labels for each image.

Python3




X = np.array(images)
y = np.array(labels)


Label Encoding:

The fit_transform method of the LabelEncoder class is used to fit the encoder to the unique labels in y and transform them into numerical values.

Python3




from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
y = le.fit_transform(y)


Shuffling the data:

  • The shuffle function is used to shuffle the order of samples and their corresponding labels.
  • X_sh contains the shuffled images.
  • y_sh contains the corresponding shuffled labels.
  • The random_state=42 argument ensures reproducibility by initializing the random number generator with a specific seed.
  • This is done to introduce randomness in the data which is useful while training.

Python3




from sklearn.utils import shuffle
X_sh, y_sh = shuffle(X, y, random_state=42)


Building the Model

The model is implemented using the Keras API with a TensorFlow backend.

The model architecture consists of the following layers:

  • Convolutional layer with 16 filters, a 3×3 kernel, and ReLU activation.
  • Max pooling layer to reduce spatial dimensions.
  • Convolutional layer with 32 filters and ReLU activation.
  • Max pooling layer.
  • Convolutional layer with 64 filters and ReLU activation.
  • Max pooling layer.
  • Convolutional layer with 128 filters and ReLU activation.
  • Max pooling layer.
  • Flatten layer to prepare for fully connected layers.
  • Dense (fully connected) layer with 128 neurons and ReLU activation.
  • Dense layer with 64 neurons and ReLU activation.
  • Dense output layer with 36 neurons and softmax activation for multiclass classification.

Python3




model = Sequential()
model.add(Conv2D(filters=16, kernel_size=(3,3), activation='relu', input_shape=(64,64,3)))
model.add(MaxPooling2D())
model.add(Conv2D(filters=32, kernel_size=(3,3),  activation='relu'))
model.add(MaxPooling2D())
model.add(Conv2D(filters=64, kernel_size=(3,3),  activation='relu'))
model.add(MaxPooling2D())
model.add(Conv2D(filters=128, kernel_size=(3,3), activation='relu'))
model.add(Flatten())
model.add(Dense(units=128, activation='relu'))
model.add(Dense(units=64, activation='relu'))
model.add(Dense(units=36, activation='softmax'))


Model compiling and training

Compiling the Model:

  • optimizer=’adam’: Adam optimization algorithm is chosen for adaptive learning rates.
  • loss=’sparse_categorical_crossentropy’: Loss function for multi-class classification with integer labels.
  • metrics=[‘accuracy’]: Monitoring accuracy during training.

Training the Model:

  • model.fit(X_sh, y_sh, validation_split=0.2, batch_size=16, epochs=10)
  • X_sh and y_sh are shuffled and preprocessed images and labels.
  • validation_split=0.2: 20% of the training data used for validation.
  • batch_size=16: Number of samples in each training iteration.
  • epochs=10: Number of passes through the entire training dataset.

Python3




model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics = ['accuracy'])
history = model.fit(X_sh, y_sh ,validation_split=0.2, batch_size=16, epochs=10)


Output:

Epoch 1/10
1032/1032 [==============================] - 87s 79ms/step - loss: 0.7324 - accuracy: 0.7997 - val_loss: 0.2487 - val_accuracy: 0.9261
Epoch 2/10
1032/1032 [==============================] - 77s 74ms/step - loss: 0.1897 - accuracy: 0.9410 - val_loss: 0.1610 - val_accuracy: 0.9544
Epoch 3/10
1032/1032 [==============================] - 77s 75ms/step - loss: 0.1284 - accuracy: 0.9553 - val_loss: 0.1720 - val_accuracy: 0.9501
Epoch 4/10
1032/1032 [==============================] - 71s 69ms/step - loss: 0.1075 - accuracy: 0.9615 - val_loss: 0.1377 - val_accuracy: 0.9617
Epoch 5/10
1032/1032 [==============================] - 71s 69ms/step - loss: 0.0870 - accuracy: 0.9699 - val_loss: 0.1620 - val_accuracy: 0.9542
Epoch 6/10
1032/1032 [==============================] - 70s 68ms/step - loss: 0.0777 - accuracy: 0.9714 - val_loss: 0.1518 - val_accuracy: 0.9615
Epoch 7/10
1032/1032 [==============================] - 70s 68ms/step - loss: 0.0656 - accuracy: 0.9752 - val_loss: 0.1838 - val_accuracy: 0.9627
Epoch 8/10
1032/1032 [==============================] - 69s 67ms/step - loss: 0.0595 - accuracy: 0.9771 - val_loss: 0.1525 - val_accuracy: 0.9603
Epoch 9/10
1032/1032 [==============================] - 69s 67ms/step - loss: 0.0580 - accuracy: 0.9778 - val_loss: 0.1965 - val_accuracy: 0.9595
Epoch 10/10
1032/1032 [==============================] - 70s 68ms/step - loss: 0.0524 - accuracy: 0.9793 - val_loss: 0.1378 - val_accuracy: 0.9629

The training history, including loss and accuracy metrics on both training and validation sets, is stored in the history variable for later analysis.

Python3




plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.legend(['loss', 'val_loss'])


Output:

Capture

Model Testing

We do similar preprocessing steps taken for the training dataset.

Python3




test_images = []
test_labels = []
 
path = '/content/data/testing_data'
 
dir_list = os.listdir(path)
for i in dir_list:
  dir = os.path.join(path, i)
  file_list = os.listdir(dir)
  for j in file_list:
    files = os.path.join(dir, j)
    img = cv2.imread(files)
    img = cv2.resize(img, (64,64))
    img = np.array(img, dtype=np.float32)
    img = img/255
    test_images.append(img)
    test_labels.append(i)


Python3




X_test = np.array(test_images)
y_test = np.array(test_labels)


Making predictions

  • preds = model.predict(X_test): Using the trained model to make predictions on the test dataset (X_test).
  • np.argmax(preds, axis=1): Obtaining the index of the class with the highest predicted probability for each sample.
  • le.inverse_transform(…): Inverse transforming the predicted indices back to the original class labels using the LabelEncoder (le).

Python3




preds = model.predict(X_test)
predicted_labels = le.inverse_transform(np.argmax(preds, axis=1))


Visualize the predictions

Python3




plt.imshow(X_test[197])
plt.title(f"Label: {predicted_labels[197]}")
plt.show()


Output:

Capture

Model Evaluation

Label Encoding for Test Data:

  • y_test = le.fit_transform(y_test): Applying label encoding to the true labels (y_test) of the test dataset using the same LabelEncoder (le) used during training.

Evaluating the Model on Test Data:

  • test_loss, test_accuracy = model.evaluate(X_test, y_test): Evaluating the trained model on the test dataset.
  • X_test: Test images.
  • y_test: True labels for the test dataset.
  • test_loss: The loss computed on the test dataset.
  • test_accuracy: The accuracy of the model on the test dataset.

Printing Test Accuracy:

  • print(f”Test Accuracy: {test_accuracy}”): Displays the test accuracy achieved by the model on the test dataset.

Python3




y_test = le.fit_transform(y_test)
test_loss, test_accuracy = model.evaluate(X_test, y_test)
print(f"Test Accuracy: {test_accuracy}")


Output:

Test Accuracy: 0.9811508059501648

We can conclude that the model has a very high accuracy of 98.61% and performs well on unseen data too.

Applications of Optical Character Recognition

  • Document Digitization: OCR plays a pivotal role in converting paper-based documents into digital formats, facilitating efficient storage, retrieval, and search functionalities. Businesses can streamline their operations by digitizing vast archives of paperwork.
  • Automated Data Entry: OCR automates the extraction of information from invoices, receipts, and forms, reducing manual data entry efforts. This not only improves accuracy but also enhances productivity in data-intensive tasks.
  • Text Extraction from Images: OCR is widely used to extract text content from images, enabling the analysis of textual information present in photographs or screenshots. This finds applications in augmented reality, image indexing, and more.
  • Accessibility for Visually Impaired: OCR technology contributes to making digital content accessible to visually impaired individuals. By converting text from images into speech or braille, OCR aids in creating an inclusive digital environment.
  • Language Translation: OCR can be integrated with language translation tools, allowing users to translate text from images or scanned documents. This is valuable for breaking down language barriers in diverse settings.

Conclusion

The article explored OCR and showcased a practical implementation using Tensorflow. The Tensorflow-based OCR model demonstrated the key steps in implementing OCR, including dataset loading, image preprocessing, model building, training, and evaluation. The model achieved a remarkable accuracy of 98.61% on the test dataset, showcasing its effectiveness in recognizing characters from diverse images.



Similar Reads

Optical Character Recognition (Ocr) Using R
OCR transforms text images into machine-readable formats. With applications ranging from receipts to license plates, we explore the process, syntax, and examples, demonstrating its versatility. In this tutorial, we will learn to perform Optical Character Recognition in R programming language using the Tesseract and Magick libraries. Optical Charact
5 min read
Image Recognition using TensorFlow
In this article, we'll create an image recognition model using TensorFlow and Keras. TensorFlow is a robust deep learning framework, and Keras is a high-level API(Application Programming Interface) that provides a modular, easy-to-use, and organized interface to solve real-life deep learning problems. Image Recognition: In Image recognition, we inp
6 min read
Sign Language Recognition System using TensorFlow in Python
The first step of any machine learning problem is finding the appropriate dataset. For Sign language recognition let's use the Sign Language MNIST dataset. It has images of signs corresponding to each alphabet in the English language. Since the sign language of J and Z requires motion, those two classes are not available in the dataset. Importing L
4 min read
Intent Recognition using TensorFlow
Intent recognition is a method of natural language processing, which deals with determining intent of a given sentence, or in simple terms "what the sentence means". It is commonly used in chatbots, virtual assistants, and other conversational AI systems to understand user requests and provide appropriate responses. In this article, We will show a
10 min read
Audio Recognition in Tensorflow
This article discusses audio recognition and also covers an implementation of a simple audio recognizer in Python using the TensorFlow library which recognizes eight different words. Audio RecognitionAudio recognition comes under the automatic speech recognition (ASR) task which works on understanding and converting raw audio to human-understandabl
8 min read
CIFAR10 DataSet in Keras (Tensorflow) for Object Recognition
The CIFAR-10 dataset is readily accessible in Python through the Keras library, which is part of TensorFlow, making it a convenient choice for developers and researchers working on machine learning projects, especially in image classification. In this article, we will explore CIFAR10 (classification of 10 image labels) from Keras/tensorflow. Table
7 min read
ML | Implement Face recognition using k-NN with scikit-learn
k-Nearest Neighbors: k-NN is one of the most basic classification algorithms in machine learning. It belongs to the supervised learning category of machine learning. k-NN is often used in search applications where you are looking for “similar” items. The way we measure similarity is by creating a vector representation of the items, and then compare
5 min read
Python | Multiple Face Recognition using dlib
This article aims to quickly build a Python face recognition program to easily train multiple images per person and get started with recognizing known faces in an image. In this article, the code uses ageitgey's face_recognition API for Python. This API is built using dlib's face recognition algorithms and it allows the user to easily implement fac
4 min read
ML | Face Recognition Using PCA Implementation
Face Recognition is one of the most popular and controversial tasks of computer vision. One of the most important milestones is achieved using This approach was first developed by Sirovich and Kirby in 1987 and first used by Turk and Alex Pentland in face classification in 1991. It is easy to implement and thus used in many early face recognition a
6 min read
ML | Face Recognition Using Eigenfaces (PCA Algorithm)
In 1991, Turk and Pentland suggested an approach to face recognition that uses dimensionality reduction and linear algebra concepts to recognize faces. This approach is computationally less expensive and easy to implement and thus used in various applications at that time such as handwritten recognition, lip-reading, medical image analysis, etc. PC
4 min read
FaceNet - Using Facial Recognition System
FaceNet is the name of the facial recognition system that was proposed by Google Researchers in 2015 in the paper titled FaceNet: A Unified Embedding for Face Recognition and Clustering. It achieved state-of-the-art results in the many benchmark face recognition dataset such as Labeled Faces in the Wild (LFW) and Youtube Face Database. They propose
5 min read
Human Activity Recognition - Using Deep Learning Model
Human activity recognition using smartphone sensors like accelerometer is one of the hectic topics of research. HAR is one of the time series classification problem. In this project various machine learning and deep learning models have been worked out to get the best final result. In the same sequence, we can use LSTM (long short term memory) mode
6 min read
Face recognition using Artificial Intelligence
The current technology amazes people with amazing innovations that not only make life simple but also bearable. Face recognition has over time proven to be the least intrusive and fastest form of biometric verification. The software uses deep learning algorithms to compare a live captured image to the stored face print to verify one's identity. Ima
15+ min read
Python - Facial and hand recognition using MediaPipe Holistic
What is MediaPipe: Object Detection is one of the leading and most popular use cases in the domain of computer vision. Several object detection models are used worldwide for their particular use case applications. Many of these models have been used as an independent solution to a single computer vision task with its own fixed application. Combinin
4 min read
Traffic Signs Recognition using CNN and Keras in Python
We always come across incidents of accidents where drivers' Overspeed or lack of vision leads to major accidents. In winter, the risk of road accidents has a 40-50% increase because of the traffic signs' lack of visibility. So here in this article, we will be implementing Traffic Sign recognition using a Convolutional Neural Network. It will be ver
6 min read
Flower Recognition Using Convolutional Neural Network
In this article, we will use Convolutional Neural Network to solve a Supervised Image Classification problem of recognizing the flower types - rose, chamomile, dandelion, sunflower, & tulip. Understanding the concept of a Convolutional Neural Network refers to this. Once, understand the concept of CNN we can start with the project. Steps to be
4 min read
Emojify using Face Recognition with Machine Learning
In this article, we will learn how to implement a modification app that will show an emoji of expression which resembles the expression on your face. This is a fun project based on computer vision in which we use an image classification model in reality to classify different expressions of a person. This project will be implemented in two parts: Bu
7 min read
Project Idea | (Dynamic Hand Gesture Recognition using neural network)
Introduction Hand gesture recognition system is used for interfacing between computer and human using hand gesture. We wish to make a windows-based application for live motion gesture recognition using webcam input in C++. This project is a combination of live motion detection and gesture identification. This application uses the webcam to detect g
3 min read
Automatic Speech Recognition using Whisper
Automatic Speech Recognition (ASR) can be simplified as artificial intelligence transforming spoken language into text. Its historical journey dates back to a time when developing ASR posed significant challenges. Addressing diverse factors such as variations in voices, accents, background noise, and speech patterns proved to be formidable obstacle
10 min read
Automatic Number Plate Recognition System using EasyOCR
Automatic License/Number Plate Recognition (ANPR) is an image processing technique used to identify a car based on its number plate. In this article, we'll walk through the steps to implement ANPR using Python. Techniques for ANPR are: License Plate Recognition with OpenCV and Tesseract OCRAutomatic License/Number Plate Recognition System with Easy
7 min read
Phoneme Recognition using Machine Learning
Phoneme recognition in Natural Language Processing (NLP) is a main component in developing speech recognition systems. Phonemes are the smallest sound units in a language that can distinguish one word from another. Recognising these phonemes accurately is important for converting spoken language into text. Phoneme recognition is useful in applicati
7 min read
Automatic Speech Recognition using CTC
We use speeches to express ourselves. But sometimes it is crucial to store our speech in text format. One such technology is Automatic Speech Recognition which converts spoken language into written text. In this article, we will implement Automatic Speech Recognition using Connectionist Temporal Classification (CTC). In various real-time applicatio
8 min read
Handwritten Digit Recognition using Neural Network
Introduction:Handwritten digit recognition using MNIST dataset is a major project made with the help of Neural Network. It basically detects the scanned images of handwritten digits. We have taken this a step further where our handwritten digit recognition system not only detects scanned images of handwritten digits but also allows writing digits o
9 min read
Main Loopholes in TensorFlow - Tensorflow Security
TensorFlow is an open-source machine-learning framework widely used for building, training, and deploying machine-learning models. Despite its popularity and versatility, TensorFlow is not immune to security vulnerabilities and loopholes. Some of the common security loopholes in TensorFlow are related to data privacy, session hijacking, and lack of
6 min read
Why TensorFlow is So Popular - Tensorflow Features
In this article, we will see Why TensorFlow Is So Popular, and then explore Tensorflow Features. TensorFlow is an open-source software library. It was originally developed by researchers and engineers working on the Google Brain Team within Google’s Machine Intelligence research organization for the purposes of conducting machine learning and deep
3 min read
Tensorflow 1.xvs. Tensorflow 2.x: What's the Difference?
TensorFlow is an end-to-end open-source machine learning platform that contains comprehensive tools, libraries and community resources. It is meant for developers, data scientists and researchers to build and deploy applications powered by machine learning. TensorFlow was essentially built to scale, developed by Google Brain team, TensorFlow accele
6 min read
How to migrate from TensorFlow 1.x to TensorFlow 2.x
The introduction of TensorFlow 2. x marks a significant advance in the strong open-source machine learning toolkit TensorFlow. TensorFlow 2.0 introduces significant API changes, making manual code upgrades tedious and error prone. TensorFlow 2. x places an emphasis on user-friendliness and optimizes the development process, whereas TensorFlow 1. x
7 min read
Pattern Recognition | Basics and Design Principles
Prerequisite – Pattern Recognition | Introduction Pattern Recognition System Pattern is everything around in this digital world. A pattern can either be seen physically or it can be observed mathematically by applying algorithms. In Pattern Recognition, pattern is comprises of the following two fundamental things: Collection of observationsThe conc
4 min read
Applications of Pattern Recognition
Pattern Recognition is the science of making inferences from the perceptual data using the tools from statistics, probability, computational geometry, machine learning, signal processing and algorithm design. The applications of pattern recognition are: Machine Vision: A machine vision system captures images via a camera and analyzes them to produc
2 min read
Object Detection vs Object Recognition vs Image Segmentation
Object Recognition: Object recognition is the technique of identifying the object present in images and videos. It is one of the most important applications of machine learning and deep learning. The goal of this field is to teach machines to understand (recognize) the content of an image just like humans do. Object Recognition Using Machine Learni
5 min read