DimitrisMel
DimitrisMel

Reputation: 65

Keras Preprocessing Rotates Image While Importing It With load_img()

I just started learning the Keras API and I am experimenting with the MNIST dataset. I got it working correctly but I have a problem with the function load_img() from the keras.preprocessing.image library, when I try to test a picture that I took. It imports a portrait oriented image as a landscape one. I took the photo with my smartphone in portrait mode and Windows correctly shows width 3024 and height 4032 pixels.

When I load that image and print the width and height it shows 4032x3024. Also when I do img.show(), it seems to have been rotated 90 degrees counterclockwise. All that is happening right after loading it, without any processing. I tried looking into the API for the load_img() and couldn't find any arguments that make it rotate while loading.

This is a dummy example to show you the problem:

from keras.preprocessing.image import load_img

img = load_img('filepath/test.jpg') # Load portrait mode image Windows says 3024x4032
width, height = img.size
print(width, height) # Prints 4032 3024
img.show() # Shows it rotated by 90 degrees counterclockwise

I want it to be imported in portrait mode. Why does it get rotated? The problem is that a picture taken in landscape mode is also imported as 4032 x 3024, so I can't differentiate between the 2 orientations. I want to be able to rotate the image if it's in portrait mode but not rotate it if it's in landscape mode.

EDIT: I just tried to load the image with Pillow and the results are exactly the same

Upvotes: 2

Views: 1476

Answers (2)

JohnnyChao
JohnnyChao

Reputation: 1

You can solve by saving image from keras again.

from tensorflow import keras

path = "file_path"
img = keras.preprocessing.image.load_img( path ) 
img = ndimage.rotate( img , 270 ) #rotate 270 degree
keras.preprocessing.image.save_img( path , img )

Upvotes: 0

Mark Setchell
Mark Setchell

Reputation: 207758

Use:

jhead -v YourImage.jpg

to check the EXIF parameter called Orientation - phone cameras set it so that images can be rotated. Try it for one image that works and another image that is "unhappy".

You can correct it with ImageMagick:

convert unhappy.jpg -auto-orient happy.jpg

Or maybe more easily with exiftool. Discussion and example here.

Upvotes: 2

Related Questions