If I understand your question correctly, the os.walk
function is what you need. It walks the file tree recursively and returns all folder and file names within each directory. Check the documentation for details. Here's how you would use it to compute the mean and standard deviation for each image file in a folder:
import os
IMAGE_FORMATS = {'.jpg', '.jpeg', '.png'}
for root_path, _, filenames in os.walk('/path/to/your/folder'):
for filename in filenames:
_, ext = os.path.splitext(filename)
if ext in IMAGE_FORMATS:
full_path = os.path.join(root_path, filename)
im = Image.open(full_path)
stat = ImageStat.Stat(im)
img = mahotas.imread(full_path)
mean = img.mean()
print(f"Image {full_path}: mean={mean}, stddev={stat.stddev}")
Note: the difference of os.walk
to os.listdir
is that os.walk
walks the file tree recursively, i.e., it will also walk through each sub-folder and look for images there. os.listdir
only lists the files and directories of exactly the folder you provide, but doesn't walk through sub-folders.