1

Just like the title says I m trying to Load an image file into a numpy array with Exif orientation support. I m doing this to Prevents upside-down and sideways images for face_recognition as it does not work on pictures taking by Iphones. To fix that I m using this script:

import matplotlib.pyplot as plt
import image_to_numpy

img = image_to_numpy.load_image_file("my_file.jpg")

plt.imshow(img)
plt.show()

This works for one image but I want to create a loop to do this with multiple images in a folder and save it in a different folder. Any idea on how to do that ?

Are you talking about something like this. I m pretty sure I m missing something in this below:

import glob
import os
for i in range(10)
  filepath = glob.glob(os.path.join('path/images/', *.jpg))
  try:
      image=Image.open(filepath)

      for orientation in ExifTags.TAGS.keys():
          if ExifTags.TAGS[orientation]=='Orientation':
              break

      exif=dict(image._getexif().items())

      if exif[orientation] == 3:
          image=image.rotate(180, expand=True)
      elif exif[orientation] == 6:
          image=image.rotate(270, expand=True)
      elif exif[orientation] == 8:
          image=image.rotate(90, expand=True)

    image.save(filepath)
    image.close()
  except (AttributeError, KeyError, IndexError):
    # cases: image don't have getexif
    pass ```

Zargaf
  • 124
  • 1
  • 1
  • 11

1 Answers1

1

I found this answer: https://stackoverflow.com/a/26928142/12076702.

The only changes you would need to make is to change filepath in image=Image.open(filepath) to the original image file path and this filepath, image.save(filepath) to the file path you want to save the image to.

You can use glob.glob() to get all the image file paths of a format of your choice in the specified directory by doing something like:

import glob
import os

filepaths = glob.glob(os.path.join('path', 'to', 'my', 'directory', '*.jpg'))

Then just do a for loop, opening the images, modifying them and finally saving them in the directory of you choice. Hope this helps.

BOB
  • 103
  • 1
  • 6
  • Are you talking about something like this : See above. – Zargaf Jun 18 '20 at 11:18
  • `glob.glob()` will return a list of all the file paths that meet the specified requirements. You need to loop through all those. Here's some code I wrote on pastebin that should do that: https://pastebin.com/xDbt1dzt – BOB Jun 18 '20 at 17:38