pythonimagestatisticsmeanstdev

How to sort the images by filename, and then calculate the standard deviation and mean (Python)


I would like to ask if is there any method to sort the filename (ascending order) of the image files first, followed by doing the calculation of the standard deviation and mean of each image file?

dir_path = "The file path"
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)

This is what I have done. Any suggestion to add or edit it?


Solution

  • I'm not sure what you mean my "it shows the result according to the filename so that it won't be shuffled as hard as indicating each image's value".
    Do you mean the output should tally with the filename? For example:

    import numpy as np
    from PIL import Image, ImageStat
    import mahotas
    import os
    
    dir_path = os.getcwd()
    fileext = ('.png', 'jpg', 'jpeg')
    listOfFiles = os.listdir(dir_path)
    listOfImageFiles = [imageFile for imageFile in listOfFiles if imageFile.endswith(fileext)]
    listOfImageFiles = sorted(listOfImageFiles, key=lambda x: x.lower())
    
    for imageFile in listOfImageFiles:
        im = Image.open(os.path.join(dir_path, imageFile))
        stat = ImageStat.Stat(im)
        img = mahotas.imread(os.path.join(dir_path, imageFile))
        print(imageFile, ' | ', img.mean(), ' | ', np.mean(stat.stddev))
    

    Output:

    amp2.jpg | 133.79356876314816 | 29.274617422200183
    SYxmp.jpg | 145.14824510932107 | 92.56919860284195
    WTF.jpg | 128.297026314749 | 46.0273062005517
    

    Also, I would prefer not to use mean as a variable name. These are Python reserved words mean and sum and stddev etc.