Aparna Prasad
Aparna Prasad

Reputation: 91

reading multiple images in python based on their filenames

i have a folder of 100 images of human eye. i have 50 files named retina and 50 files named mask in that folder. i need to read all the images named retina1, retina2.....retina 50 and store them in an object retina. and similarly for mask images.

i could read all the files in a folder based on the code below. but not sure how to read them based on their filenames.i.e to read all the images of retina and mask separately. as i need to implement image segmentation and cnn classifier later.

for i in os.listdir():
   f = open(i,"r")
   f.read()
   f.close()

Upvotes: 1

Views: 111

Answers (2)

Fabian
Fabian

Reputation: 1150

I would use the glob module to get the path to the correct filenames. Reference glob

import glob

retina_images = glob.glob(r"C:\Users\Fabian\Desktop\stack\images\*retina*")
mask_images = glob.glob(r"C:\Users\Fabian\Desktop\stack\images\*mask*")
print(retina_images)
print(mask_images)

Now you can use the path list to read in the correct files.

In my case my images located under: C:\Users\Fabian\Desktop\stack\images\ you can use the * as a wildcard.

EDIT:

import glob

images = {}
patterns = ["retina", "mask"]
for pattern in patterns:
    images[pattern] = glob.glob(r"C:\Users\fabia\Desktop\stack\images\*{}*".format(pattern)) 
print(images)

Generate a dict out of your searching patterns could be helpful.

Upvotes: 4

Frederik Højlund
Frederik Højlund

Reputation: 197

You can limit the loop to match certain filenames by combining the loop with a generator expression.

for i in (j for j in os.listdir() if 'retina' in j):
   f = open(i,"r")
   f.read()
   f.close()

Upvotes: 1

Related Questions