How to automate calculation of standard deviation and mean of many images in a folder (Python)

Question:

I would like to learn how to let it continuously run to calculate every single image in a folder of standard deviation and mean of the images.

my current code is like this, it’s basic manual code…

For current code is this it:

im = Image.open(r'path of the image')
stat = ImageStat.Stat(im)
img = mahotas.imread(r'path of the image')
mean = img.mean()
print(str(mean))
print(stat.stddev)
Asked By: Neko Lim

||

Answers:

Read the entire files in the directory by listdir and iterate the files through for loop

import os
from PIL import Image, ImageStat

dir_path = "Your Directory/Image Folder/"
listOfImageFiles = os.listdir(dir_path)
fileext = ('.png', 'jpg', 'jpeg')

for imageFile in listOfImageFiles:
    if imageFile.endswith(fileext):
       im = Image.open(os.path.join(dir_path,imageFile))
       stat = ImageStat.Stat(im)
       img = mahotas.imread(os.path.join(dir_path,imageFile))
       mean = img.mean()
       print(str(mean))
       print(stat.stddev)
Answered By: Hari E

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.

Answered By: Green绿色
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.