Skip to content Skip to sidebar Skip to footer

Reading Images While Maintaining Folder Structure

I have to write a matlab script in python as apparently what I want to achieve is done much more efficiently in Python. So the first task is to read all images into python using op

Solution 1:

The first problem is that n isn't a number or index, it is a string containing the path name. To get the index, you can use enumerate, which gives index, value pairs.

Second, unlike in MATLAB you can't assign to indexes that don't exist. You need to pre-allocate your image array or, better yet, append to it.

Third, it is better not to use the variable file since in python 2 it is a built-in data type so it can confuse people.

So with preallocating, this should work:

images = [None]*len(sub_f)
for n, cursub in enumerate(sub_f):
    path_now = os.path.join(path, cursub, '*.pgm')
    images[n] = [cv2.imread(fname) for fname in glob.glob(path_now)]

Using append, this should work:

for cursub in sub_f
    path_now = os.path.join(path, cursub, '*.pgm')
    images.append([cv2.imread(fname) for fname in glob.glob(path_now)])

That being said, there is an easier way to do this. You can use the pathlib module to simplify this.

So something like this should work:

from pathlib import Path

mypath = Path('/home/university/Matlab/att_faces')
images = []

for subdir in mypath.iterdir():
    images.append([cv2.imread(str(curfile)) for curfile in subdir.glob('*.pgm')])

This loops over the subdirectories, then globs each one.

This can even be done in a nested list comprehension:

images = [[cv2.imread(str(curfile)) for curfile in subdir.glob('*.pgm')]
          for subdir in mypath.iterdir()]

Solution 2:

It should be the following:

import ospath = '/home/university/Matlab/att_faces'

sub_f = os.listdir(path)
print(sub_f)    #--- this will print all the files present in this directory ---

#--- this a list to which you will append all the images ---
images = []


#--- iterate through every file in the directory and read those files that end with .pgm format ---
#--- after reading it append it to the list ---for n in sub_f:
    if n.endswith('.pgm'):
        path_now = os.path.join(path, n)
        print(path_now)
        images.append(cv2.imread(path_now, 1))

Solution 3:

import cv2
import os
import glob

path = '/home/university/Matlab/att_faces'

sub_f = os.listdir(path)
images = []

#read the images
for folder in sub_f:
    path_now = os.path.join(path, folder, '*.pgm')
    images.append([cv2.imread(file) for file in glob.glob(path_now)])

#display the images
for folder in images:
    for image in folder:
        cv2.imshow('image',image)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

Post a Comment for "Reading Images While Maintaining Folder Structure"