I have 67 images in a directory with names as:
JavaScript
x
16
16
1
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
2
3
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
4
5
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
6
.
7
.
8
.
9
.
10
.
11
.
12
.
13
.
14
.
15
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
16
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:
JavaScript
1
26
26
1
from glob import glob
2
from os import path
3
4
DIRECTORY = '.' # directory containing image files
5
PREFIX = '260'
6
7
def process(filename):
8
print(filename) # do your real processing here
9
10
def getkey(s):
11
t = path.basename(s).split('_')
12
assert len(t) == 3
13
assert t[1].startswith(PREFIX)
14
a = t[1][len(PREFIX):]
15
b, _ = path.splitext(t[2])
16
try:
17
return int(a), int(b)
18
except ValueError:
19
return 0, 0
20
21
22
filelist = glob(path.join(DIRECTORY, 'Im_*'))
23
24
for file in sorted(filelist, key=getkey):
25
process(file)
26