Straighten a poorly scanned text document with deskew

Share this post

Straighten up, why?

You need to recover data from previously scanned document. Obviously you immediately think of using an OCR ( see this article which shows how to use Tesseract )… but there you are, if your document is of good quality, it is not aligned correctly. he is askew! and your OCR cannot interpret its content.

This is quite normal, in fact you must first straighten the document so that it looks straight, ready for the application of this OCR. We will see in this article how to use Python and the deskew library.

The Python deskew library

What’s great about the Python universe is that there is a library for everything. After some quick research on your search engine you will certainly find quite a few begging to be tried.

I’ll show you one of the simplest: the deskew library which you can find here .

Installation is quick and easy (the underlying code is also quick, if you have time to look at it). For information, this library uses another much better known scikit-image library , which is also very useful for managing image data.

pip install deskew


The goal is rather simple, we need to retrieve the textual information from the following image:

Just to check what I told you in the introduction, let’s try to use Tesseract directly on this image:

    from PIL import Image
except ImportError:
    import Image
import pytesseract
image1 ='img_35h.jpg')
pytesseract.image_to_string(image1, lang='fra')

Indeed, Tesseract sees absolutely nothing!

Straighten the image with deskew

First of all, let’s import the necessary libraries:

import numpy as np
from skimage import io
from skimage.transform import rotate
from skimage.color import rgb2gray
from deskew import determine_skew
from matplotlib import pyplot as plt

Then create a small function that will allow us to straighten the image:

def deskew(_img):
    image = io.imread(_img)
    grayscale = rgb2gray(image)
    angle = determine_skew(grayscale)
    rotated = rotate(image, angle, resize=True) * 255
    return rotated.astype(np.uint8)

This function is quite simple. The deskew library indeed encapsulates all the calls necessary for recovery … except perhaps the conversion to gray levels which is an essential step to detect tilt angles.

Then let’s create a small function to test and see the result (with matplotlib ) of our adjustments:

def display_avant_apres(_original):
    plt.subplot(1, 2, 1)
    plt.subplot(1, 2, 2)

The result

I took a few tilted images to test the result. A first test with a tilt of 35 degrees clockwise:


Then with an inclination of 15 degrees counterclockwise:


The result seems rather conclusive, doesn’t it? let’s try to use Tesseract now on this image:

io.imsave('output.png', deskew('img_35h.jpg'))
image1 ='output.png')
pytesseract.image_to_string(image1, lang='fra')

And There you go ! the result is the expected one.

You want to automate this type of task with the RPA Blue Prism … take a look at this article.

The video below shows the solution in action:

Share this post

Benoit Cayla

In more than 15 years, I have built-up a solid experience around various integration projects (data & applications). I have, indeed, worked in nine different companies and successively adopted the vision of the service provider, the customer and the software editor. This experience, which made me almost omniscient in my field naturally led me to be involved in large-scale projects around the digitalization of business processes, mainly in such sectors like insurance and finance. Really passionate about AI (Machine Learning, NLP and Deep Learning), I joined Blue Prism in 2019 as a pre-sales solution consultant, where I can combine my subject matter skills with automation to help my customers to automate complex business processes in a more efficient way. In parallel with my professional activity, I run a blog aimed at showing how to understand and analyze data as simply as possible: Learning, convincing by the arguments and passing on my knowledge could be my caracteristic triptych.

View all posts by Benoit Cayla →

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Privacy Preference Center


What is a cookie and what is it used for?

A cookie (or connection witness) is a text file that can be saved, subject to your choices, in a dedicated space on the hard drive of your terminal (computer, tablet, etc.) when consulting a online service through your browser software.
It is transmitted by a website's server to your browser. Each cookie is assigned an anonymous identifier. The cookie file allows its issuer to identify the terminal in which it is registered during the period of validity or registration of the cookie concerned. A cookie cannot be traced back to a natural person.

When you visit this site, it may be required to install, subject to your choice, various statistical cookies.
What types of cookies are placed by the website?

Google Analytics & Matomo Statistics Cookies

These cookies are used to establish statistics of visits to my site and to detect navigation problems in order to monitor and improve the quality of our services.
Exercise your choices according to the browser you use

You can configure your browser at any time in order to express and modify your wishes in terms of cookies, and in particular regarding statistical cookies. You can express your choices by setting your browser to refuse certain cookies.

If you refuse cookies, your visit to the site will no longer be counted in Google Analytics & Matomo and you will no longer be able to benefit from a number of features that are nevertheless necessary to navigate certain pages of this site.
However, you can oppose the registration of cookies by following the operating procedure available below:

On Internet Explorer
1. Go to Tools> Internet Options.
2. Click on the privacy tab.
3. Click on the advanced button, check the box "Ignore automatic management of cookies".

On Firefox
1. At the top of the Firefox window, click the Firefox button (Tools menu in Windows XP), then select Options.
2. Select the Privacy panel.
3. Configure Conservation rules: to use the personalized parameters for the history.
4. Uncheck Accept cookies.

On Chrome
1. Click on the wrench icon which is located in the browser toolbar.
2. Select Settings.
3. Click Show advanced settings.
4. In the “Confidentiality” section, click on the Content settings button.
5. In the "Cookies" section, you can block cookies and data from third-party sites

On Safari
1. Go to Settings> Preferences
2. Click on the Privacy tab
3. In the "Block cookies" area, check the "always" box.

About Opera
1. Go to Settings> Preferences
2. Click on the advanced tab
3. In the "Cookies" area, check the "Never accept cookies" box.
social network sharing cookies

On certain pages of this site there are buttons or modules of third-party social networks that allow you to use the functionalities of these networks and in particular to share content on this site with other people.
When you go to a web page on which one of these buttons or modules is located, your browser can send information to the social network which can then associate this visualization with your profile.

Social network cookies, over which this site has no control, may then be placed in your browser by these networks. I invite you to consult the confidentiality policies specific to each of these social networking sites, in order to become aware of the purposes for using the browsing information that social networks can collect using these buttons and modules.
- Twitter
- Google+
- LinkedIn

Statistiqcs only

Fork me on GitHub