Title: Correct EXIF orientation when you load images in Python
When you take a picture with a rotated camera, the resulting picture is stored rotated. EXIF information embedded in the picture tells you how the image is rotated, but what you normally want to do is just load the picture right side up.
PIL doesn't automatically fix an image's orientation, but it's easy to twist PIL's electronic arm: Simply call the ImageOps.exif_transpose function.
The heart of this example is the following statement.
with ImageOps.exif_transpose(image) as pil_image:
The program earlier loads the image file into the variable image. Then this statement calls ImageOps.exif_transpose to transform the image so it has the normal orientation and you can display it normally.
If the image was originally in the normal TopLeft orientation, PIL does nothing and the image keeps its orientation. If the image had some other orientation, PIL removes the EXIF Orientation tag so the image now has Unknown orientation.
Oriented Tools
Note that some tools "helpfully" fix an image's orientation for you. In Windows, for example, File Explorer automatically shows images right side up. That makes it extra confusing when you find such an image appears sideways when you open it in a Python program.
Similarly, if you open a rotated image in MS Paint, Paint displays it right side up.
You can use Paint to fix rotated images, however, by rotating the image to the left, rotating it back to the right, and then saving it. That works if you only need to fix one or two images, but if you expect this to be a common issue, you can use ImageOps.exif_transpose in your Python programs.
Conclusion
If you have one or two images that have unusual orientations, you can use Paint or a similar tool to fix them. If you run into rotated images frequently, just add ImageOps.exif_transpose to your program and you should be able to ignore that issue.
Download the example to experiment with it and to see additional details.
|