0

I created a simple Python program to flip multiple image files and save it to another folder. The problem that I'm having is the files are loaded into an array while disregarding the file numbering, thus the output files didn't have the same naming as the original file (excluding 0.jpg and 1.jpg).

Original picture and flipped picture comparison

Below are the code I use to flip the images.

# import modules
from tqdm import tqdm
import numpy as np
import glob
import cv2

# directory path to images
training_images = glob.glob("original_images/*.jpg")
# load the images into an array
image_array = np.array([cv2.imread(file) for file in training_images])
# find how many contents exist inside the array
array_length = np.size(image_array)

# flip the images and save to flipped_images/ folder
for x in range(array_length):

    number = str(x)
    flipped = np.flip(image_array[x], 1)
    cv2.imwrite('flipped_images/' + number + '.jpg', flipped)

There is any way for me to make sure the data are loaded in sequence according to the filename? Thanks in advance.

ヲヲヲ
  • 61
  • 7
  • 1
    ``glob`` will sort your images using string order, for example. ``'10.jpg'`` will be in the array before ``'2.jpg'``. When you use ``range()``, you are getting numbers from 0,1,2,3...10. Possible duplicate of [Does Python have a built in function for string natural sort?](https://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort) – cap Oct 05 '18 at 12:11
  • 1
    you could just use the input string as the filename for your flipped image. – Dschoni Oct 05 '18 at 12:31

1 Answers1

1

Why not create the output name from the input name?

# import modules
from tqdm import tqdm
import numpy as np
import glob
import cv2

# directory path to images
training_images = glob.glob("original_images/*.jpg")

for filename in training_images:
  image = np.array(cv2.imread(filename))
  flipped = np.flip(image, 1)
  out_path = filename.replace("original_images","flipped_images")
  cv2.imwrite(out_path, flipped)
Dschoni
  • 3,714
  • 6
  • 45
  • 80