0

There is 2498 images(with index from 0 to 2497) in a folder which its address is inserted at'image_folder'. the format of images names is as [STFT_Train_0, STFT_Train_1,...., STFT_Train_2497]. i've tried to import these images by Considering the order of the indexes but the code which is shown below import images without considering the order of image indexes. Thanks if anyone can help to import them by considering image index order and convert them to numpy array.

image_folder = 'D:\\thesis\\Paper 3\\Feature Extraction\\two_dimension_Feature_extraction\\STFT_Feature\\STFT_Train'
images = [img for img in os.listdir(image_folder) if img.endswith(".png")]
Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62
sepehr
  • 9
  • 4

2 Answers2

0

Sort using the numerical part of your file name.

image_folder = 'D:\\thesis\\Paper 3\\Feature Extraction\\two_dimension_Feature_extraction\\STFT_Feature\\STFT_Train'
images = [image for image in os.listdir(image_folder) if image.endswith(".png")]
images = sorted(images, key=lambda string: int(string.split("_")[-1][:-4]))

The sorting key that we use will take each file name, for example "STFT_Train_2497.png", extract the last part which is "2497.png", remove the suffix and turn it into the integer 2497. This ensures you get your list sorted like 0, 1, 2, 3, 4, ... instead of "0", "1", "10", "100", "1000", ....

Guimoute
  • 4,407
  • 3
  • 12
  • 28
0

A hacky solution would be to generate the files manually if they all share the same base file name.

image_folder = 'D:\\thesis\\Paper 3\\Feature Extraction\\two_dimension_Feature_extraction\\STFT_Feature\\STFT_Train'
// generates a list of file names like 'STFT_Train_1.png', 'STFT_Train_2.png', etc
images = ['STFT_Train_{}.png'.format(ind) for ind in range(2498)]

If you wanted to add more training samples, this solution doesn't scale very well, but another hacky solution could be:

image_folder = image_folder = 'D:\\thesis\\Paper 3\\Feature Extraction\\two_dimension_Feature_extraction\\STFT_Feature\\STFT_Train'
// returns the number of png files in [image_folder]
num_images = len([img for img in os.listdir(image_folder) if img.endswith(".png")])
images = ['STFT_Train_{}.png'.format(ind) for ind in range(num_images )]
nablag
  • 176
  • 1
  • 7
  • Thanks you. the second one worked with just a little bit changes. i just changed range(num_images) to range(0,len(num_images)) – sepehr Dec 05 '20 at 17:33
  • I believe range(X) is the same thing as as range(0, X). But glad to help! – nablag Dec 05 '20 at 17:36