2

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).

no error happens but the building images is not placed respectively in tensor.

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

variable explorer

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

3 Answers3

1

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.

venkata krishnan
  • 1,961
  • 1
  • 13
  • 20
  • if you find this answer useful, please mark this as accepted answer, which will help the future users. – venkata krishnan Aug 27 '19 at 07:15
  • 1
    thank you venkata krishnan. I'm using your answers and others to find out my problem.names = glob.glob('building_*.tif') list_names= sorted(names, key=lambda elem: int(elem[elem.find('_')+1:elem.find('.')])) – Frank Taylor Aug 27 '19 at 09:09
  • i just missed converting it to int. you did it. thanks for accepting the answer. :-) – venkata krishnan Aug 27 '19 at 09:22
0

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.

Ching Liu
  • 21
  • 3
0

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('.')]))