如何自动计算一个文件夹中许多图像的标准差和平均值(Python)



我想学习如何让它连续运行来计算每个文件夹中的图像的标准差和平均值。

我现在的代码是这样的,它是基本的手工代码…

对于当前代码是这样的:

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)

通过listdir读取目录中的所有文件,并通过for循环遍历这些文件

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)

如果我正确理解你的问题,os.walk函数是你所需要的。它递归遍历文件树并返回每个目录中的所有文件夹和文件名。查看文档了解详细信息。下面是如何使用它来计算文件夹中每个图像文件的平均值和标准差:

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}")

注意:os.walkos.listdir的不同之处在于os.walk递归地遍历文件树,也就是说,它也会遍历每个子文件夹并在那里查找图像。os.listdir只列出您提供的文件夹的文件和目录,但不遍历子文件夹。

最新更新