1

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?

blackraven
  • 5,284
  • 7
  • 19
  • 45
Neko Lim
  • 53
  • 5

1 Answers1

1

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.

blackraven
  • 5,284
  • 7
  • 19
  • 45
  • yes thats the output im looking for, because my output value not sure why is not arrange to the filename accordingly, maybe have somethings messed up. Update: I have tried your code and it have a error whereby "NameError: name 'listOfImageFiles' is not defined" – Neko Lim Jan 16 '23 at 01:07
  • perhaps you might have used a Python reserved word as a variable. I have experienced using `sum` as a variable name with lots of weird output, until I restarted the Kernel and used `total` instead – blackraven Jan 16 '23 at 01:12
  • edited my code.. please restart Kernel and try again – blackraven Jan 16 '23 at 01:18
  • Thanks, mate. The code worked properly and I just reload my kernel + edit my previous variable – Neko Lim Jan 16 '23 at 01:27