How to rotate an image a set number of degrees in Python
Image rotation is a pretty basic feature, one that can be used from everything from photo apps to optical character recognition (OCR). Setting it up is not really as straightforward as you might think at first. So how about we skip all that and use an API to take care of things. This is going to save us a ton of time, just wait and see.
So, with pip install, we can set up our client and roll right along.
pip install cloudmersive-image-api-client
Next is our API function call:
from __future__ import print_functionimport timeimport cloudmersive_image_api_clientfrom cloudmersive_image_api_client.rest import ApiExceptionfrom pprint import pprint# Configure API key authorization: Apikeyconfiguration = cloudmersive_image_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_image_api_client.EditApi(cloudmersive_image_api_client.ApiClient(configuration))degrees = 1.2 # float | Degrees to rotate the image; values range from 0.0 to 360.0.image_file = '/path/to/file' # file | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.try:# Rotate an image any number of degreesapi_response = api_instance.edit_rotate(degrees, image_file)pprint(api_response)except ApiException as e:print("Exception when calling EditApi->edit_rotate: %s\n" % e)
So now we just need to input our image and set the degrees of rotation. The API will handle the actual image processing, then return the results. This function can be paired with our other function for determining scanned document angle, called preprocessing_get_page_angle, which is part of our OCR API.