Reputation: 21
I'm beginner in python.my problem happens when i want to import some image from a folder with names.
my files: building_3.tif building_21.tif building_22.tif building_25.tif building_27.tif building_36.tif building_44.tif building_49.tif building_53.tif building_70.tif building_101.tif building_248.tif building_1002.tif
i just want to import them and placed in a nd matrix(tensor) respectively. for example if we have (14,264,120) tensor , building_1002 should be placed in last (13,264,120) and building_3 placed in first(0,264,120).
import numpy as np
import glob
import os
from PIL import Image
path = '/path/'
image_list = []
all_data =np.zeros((14,264,120))
i=0
for filename in glob.glob(path + '/building_*.tif'):
im=Image.open(filename)
image_list.append(im)
n = len(image_list)
all_data[i,:,:]=im
i=i+1
the respectively that happens is : building_1002.tif (264, 120, 4) building_101.tif (264, 120, 4) building_21.tif (264, 120, 4) building_22.tif (264, 120, 4) building_23.tif (264, 120, 4) building_248.tif (264, 120, 4) building_25.tif (264, 120, 4) building_27.tif (264, 120, 4) building_3.tif (264, 120, 4) building_36.tif (264, 120, 4) building_44.tif (264, 120, 4) building_49.tif (264, 120, 4) building_53.tif (264, 120, 4) building_70.tif (264, 120, 4)
Thanks in advance for your cooperation
Upvotes: 2
Views: 83
Reputation: 21
Thank you all. from venkata krishnan and from this link How to sort this list of strings using a substring?
the correct answer is :
names = glob.glob('building_*.tif')
list_names= sorted(names, key=lambda elem:int(elem[elem.find('_')+1:elem.find('.')]))
Upvotes: 0
Reputation: 31
It seem you only assign (14,264,120) that much space for 14*(264, 120, 4). Maybe you should assign (264,120,4*14) for enough space for the pictures.
Upvotes: 0
Reputation: 2046
You can sort the filenames beforehand
names = glob.glob(path + '/building_*.tif')
names = sorted(names,lambda x:x.split(".")[0].split("_")[1])
then use the names array to read the files in the for loop.
Upvotes: 1