im still newbie in python programming and I would like to learn how to let it continuous run to calculate every single images in a folder of standard deviation and mean of the images.
my current code is like this, its basic manual code...
`For current code is this and I know, I'm still learning to 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)`
CodePudding user response:
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)
CodePudding user response:
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.