I have 67 images in a directory with names as:
Im_2601_0 Im_2601_1 Im_2601_4 Im_2601_8 Im_2601_16 Im_2601_32 Im_2601_64 Im_2601_128 Im_2601_256 Im_2602_0 Im_2602_1 Im_2602_4 Im_2602_8 Im_2602_16 Im_2602_32 Im_2602_64 Im_2602_128 Im_2602_256 Im_2603_0 Im_2603_1 Im_2603_4 Im_2603_8 Im_2603_16 Im_2603_32 Im_2603_64 Im_2603_128 Im_2603_256 . . . . . . . . . Im_26067_0 Im_26067_1 Im_26067_4 Im_26067_8 Im_26067_16 Im_26067_32 Im_26067_64 Im_26067_128 Im_26067_256
Files are jpg files Im_260x_y where x is the number of images 1..67, y are 0, 1, 4, 8, 16, 32, 64, 128, 258. These files are randomly stored in the directory.
I want to process the files in sorted order (same order which I have written above i.e Image 1 for all of 0, 1, 4, 8, 16, 32, 64, 128, 258. Then image 2 for all of 0, 1, 4, 8, 16, 32, 64, 128, 258 and so on).
How can I write Python code for this?
Advertisement
Answer
You could do this:
from glob import glob
from os import path
DIRECTORY = '.' # directory containing image files
PREFIX = '260'
def process(filename):
print(filename) # do your real processing here
def getkey(s):
t = path.basename(s).split('_')
assert len(t) == 3
assert t[1].startswith(PREFIX)
a = t[1][len(PREFIX):]
b, _ = path.splitext(t[2])
try:
return int(a), int(b)
except ValueError:
return 0, 0
filelist = glob(path.join(DIRECTORY, 'Im_*'))
for file in sorted(filelist, key=getkey):
process(file)