The Horizon Detection microservice from Algorithmia is an easy-to-use API which takes an image (URL or base64-encoded file) and attempts to find the horizon.
This Python script allows you to specify an input image, passes it through the horizon-detection service, and straightens out the image (while optionally cropping and resampling it).
For the full blog post related to this recipe, see How to Rotate Images in Python Using a Horizon Detection Algorithm.
Create a free Algorithmia account, and install the Algorithmia Python client and the Pillow image-manipulation library:
Detailed instructions can be found in the blog post.
How To Run the Script
First, edit the script and replace
your_api_key with your Algorithmia API Key
/some/filename.jpg with a path to a JPEG image on your local filesystem, and
/some/outputfile.jpg with the desired path for the output file.
Use the command line, and navigate to the folder with your Python file and run: