×

Image to Text in python

Processing out information from an image is a very big task in all the fields of work such as in development and business sector. The process of converting an electronical image into encoded form of text is called as OCR. OCR stands for Optical Character Recognition. OCR works under the research categories of Artificial intelligence and machine learning, pattern recognition and computer technologies. This is done in such a way that the image is processed under the machine learning algorithms, and it is certainly known that some kind of information is present in the image.

For understanding the image to text process in Python we need to import two different types of libraries and as followed:

  • Pytesseract
  • Pillow

Tesseract is an open-Source tool which is used to process and extract text from images. To make use of Tesseract in Python we need the help of pytesseract which is one of a wrappers for the tesseract. As we are working the image processing, we need the help of pillow library which is used to perform operation on it in Python.

The commands for installing the pytesseract and pillow in Python are:

pip install pytesseract
pip install pillow

We need to mainly focus on the paths of the files as it will be helpful in the further execution of code. For most of the directories the path is maintained as:

C:\\ProgramFiles\\Tesseract\\tesseract.exe

Process to be Followed:

  • We need to import the image firstly using PIL library for viewing image and opening the image.
  • Then by using the pytesseract module from the main tesseract library which we use it for the text prediction and extraction from the image.
  • After importing libraries and viewing the image, we need to define the path for the tesseract module which we installed in the first and this path will be depending upon on the location where it is installed and we need to define the path for the image file also.
  • We need to define the path for tesseract cmd variable, this helps in finding the text in image and to extract it.
  • After defining all the paths, we need to pass the image object to image string function. This takes input as image object and returns the text data present it.
  • At last, we display the text which is extracted from the image.

Example:

We are uploading an image for the reference and the code:

Image to Text in Python

Code:

from PIL import Image
from pytesseract import pytesseract
#defining the path for image and tesseract.exe
Path_to_tesseract = r” C:\\ProgramFiles\\Tesseract\\tesseract.exe”
imageP = r”csv\sample_texting.png”
 Image = image. open(imagep) #Viewing the image and storing the image data                                                 
#Accessing the tesseract directory
#pytesseract library setting location
Pytesseract . tesseract_cmd = path_to_tesseract
Text = pytesseract. image_to_string(image) 
#providing the image object to image_to_string ()
#Display output
print (text [; -1])

Output:

Life is beautiful

The above example code is for reading the single image and displaying the desired output.

Extracting the Text from Multiple Images at Once:

We need to import a new library named as os. This module is used for interacting with the operating system and has many built in functions embedded in it to interact with the file system. We import this library when we are needed to extract the data from multiple images.

The code for image is saved by main.py.

Here, we use iteration technique for reading the images and following the same module method as of the single image.

Example:

Image to Text in Python
Image to Text in Python
Image to Text in Python

Code:

#images uploaded
from PIL import Image
from pytesseract import pytesseract
import os
#defining the path for image and tesseract.exe
Path_to_tesseract = r” C:\\ProgramFiles\\Tesseract\\tesseract.exe”
imageP = r”images/”
#Accessing the tesseract directory
#pytesseract library setting location
Pytesseract . tesseract_cmd = path_to_tesseract
For root, dirs, file_name in os. Walk(path_to_image):
#iterate  over each file_name in the folder
For file_name in the file_name:
#Open image with PIL
img = Image.open(path_to_image+file_name)
#Extract text from image
Text = pytesseract. image_to_string(img)
Print(text)

Output:

Sample Text 1
Sample Text 2
Sample Text 3

Tesseract performs well and good when the image document has high-quality resolution and no noise in it and the scaling of the is done in appropriately.

The tesseract version 4.0 which is the latest one is very much accurate and tesseract as a good tool when it comes to scanning of documents.


Related Topics

How to Install Python In Windows

How To Install Python In Windows? Python is a language that every aspirant developer looks forward to. One thing we must keep in our mind is how to begin our hands-on...

3 minutes read.

ER diagram of the Bank Management System in python

What is an ER diagram? The full form of the ER diagram is the Entity Relationship diagram. This diagram is used in database management systems to have a rough idea of...

3 minutes read.

What Does the Percent Sign (%) Mean in Python?

In python, the percent sign is called modulo operator " %, " which returns the rest of partitioning the left-hand operand by the right-hand operand. Example: value1 = 8 value2 = 2 remainder =...

4 minutes read.

What is a Script in Python

Have you ever heard that Python is a scripting language? Or when people address a Python program file as a script? Besides programming, script generally means "a written story for...

3 minutes read.

Anonymous/Lambda Function in Python

Lambda keyword is used to declare an Anonymous function, i.e. a function that does not have any name. It is also called Anonymous functions. In python, normal functions are defined...

3 minutes read.

Attributes in python

In this article, we shall learn about attributes in python. Classes are a mix of data and functions, which in reality mean attributes and methods respectively. Typically, the body of a...

3 minutes read.

Python Logistic Regression with Sklearn & Scikit

In this article, we'll walk through a tutorial for utilising the Python Sklearn (formerly known as Scikit Learn) package to implement logistic regression. To assist you in remembering the concept,...

18 minutes read.

Decision Tree in Python

Decision Tree is one of the most essential algorithms in the area of machine learning for classification and regression. But let us first talk about the lifespan of every machine learning...

12 minutes read.

Python Dictionary popitem() method

Python Dictionary popitem() method The dictionary.popitem() method in Python removes the item that was last inserted into the dictionary. Syntax dictionary.popitem() Parameter NA Return This method returns an arbitrary element (key, value) pair from the given dictionary...

1 minute read.

How to Define a Function in Python?

What is a Function? In programming, a piece of code that executes a specific task or a group of related operations is known as a function. What does Python Functions Do? If you...

6 minutes read.

Python String endswith() method

Python String endswith() method The string.endswith() method in Python returns a Boolean value True if the string ends with the specified suffix, otherwise it returns False. Syntax endswith(suffix[, start[, end]]) Parameter suffix – This parameter represents a string or tuple...

2 minutes read.

Python AIOHTTP

Python 3.5 introduced some new syntax that makes it simpler for developers to make asynchronous programmes and packages. Aiohttp, an HTTP client/server for asyncio, is one such package. In essence,...

3 minutes read.

Subprocess Module in Python

What is a Process? Every program will have its respective system state, i.e., the state in which it is running. A program that is in a running state or in a...

7 minutes read.

Python Not Equal Operator

Python provides us with many operators to make tasks easier. There are about 7 categories of operators in Python. One of the 7 classifications is the comparison operators. Just as...

3 minutes read.

How to Parse JSON in Python

JSON The JSON, the Java Script Object Notation, is an open standard file designed for data interchange; it is light-weighted text. The JSON uses human-readable text to store and transmit the...

4 minutes read.

Python Parallel Processing

By performing more jobs concurrently, your software may complete more tasks in a shorter amount of time. These aid in solving major issues. The following subjects will be covered in...

2 minutes read.

GUI Calendar using PyQt5 in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Python Dictionary

Dictionary in Python is an unordered collection of data values, which is used to store data values like a map. Unlike different data types that hold just individual assets as...

4 minutes read.

Python GUI Programming

GUI (Graphical User Interface) GUI is a graphics-based operating system that uses icons and menus to interact with the user. Python mostly works on CLI (Command Line Interface). Widgets Any user interface has...

4 minutes read.

Python Random shuffle( ) method

The shuffle() is used to change the positions of the elements in the mutable sequences. The shuffle( ) function will change the positions of the elements in the sequence of...

3 minutes read.