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

Time:01-16

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?

CodePudding user response:

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.

CodePudding user response:

You can sort the list of image files first before processing them. You can use the sorted() function and pass it your list of image files. Additionally, if you want to sort the files in ascending order of their filenames, you can use the key argument of sorted() function and pass a lambda function that extracts the filename from the full path of the image file:

dir_path = "The file path"
listOfImageFiles = sorted(os.listdir(dir_path), key=lambda x: x.lower())

Please note that, in this code snippet I use lambda x: x.lower() that is case-insensitive file sorting.

  • Related