How to get the angle of a document page photo in Python

Properly aligning a document photo is one of the most important requirements for performing accurate optical character recognition. And before we can straighten our photo, we will need its angle of rotation. So how do we get it? Well we could prepare for a lengthy coding session… or just use an API to get the job done.

So first up, our installation:

pip install cloudmersive-ocr-api-client

That will install our client and allow us to continue to calling this function here:

from __future__ import print_functionimport timeimport cloudmersive_ocr_api_clientfrom cloudmersive_ocr_api_client.rest import ApiExceptionfrom pprint import pprint# Configure API key authorization: Apikeyconfiguration = cloudmersive_ocr_api_client.Configuration()configuration.api_key['Apikey'] = 'YOUR_API_KEY'# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed# configuration.api_key_prefix['Apikey'] = 'Bearer'# create an instance of the API classapi_instance = cloudmersive_ocr_api_client.PreprocessingApi(cloudmersive_ocr_api_client.ApiClient(configuration))image_file = '/path/to/file' # file | Image file to perform OCR on.  Common file formats such as PNG, JPEG are supported.try:# Get the angle of the page / document / receiptapi_response = api_instance.preprocessing_get_page_angle(image_file)pprint(api_response)except ApiException as e:print("Exception when calling PreprocessingApi->preprocessing_get_page_angle: %s\n" % e)

From there, input your document photo into preprocessing_get_page_angle and you are good to go.

Image for post
Image for post

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store