You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python自动计算文件夹中所有图像的均值与标准差

自动批量计算文件夹内图像的均值与标准差

实现思路

先批量处理文件夹内已有的所有图像,再通过监听文件夹变化,自动对新加入的图像完成计算。

依赖准备

若需要监听文件夹新增文件,先安装所需依赖:

pip install pillow mahotas watchdog

核心代码实现

import os
from PIL import Image, ImageStat
import mahotas
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

# 定义需要处理的图像扩展名
IMAGE_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.bmp', '.gif')

def calculate_image_stats(image_path):
    """计算单张图像的均值和标准差"""
    try:
        # 使用PIL计算标准差
        im = Image.open(image_path)
        stat = ImageStat.Stat(im)
        stddev = stat.stddev
        
        # 使用mahotas计算均值
        img = mahotas.imread(image_path)
        mean = img.mean()
        
        print(f"文件: {os.path.basename(image_path)}")
        print(f"均值: {mean:.4f}")
        print(f"标准差: {[round(s,4) for s in stddev]}")
        print("---")
    except Exception as e:
        print(f"处理文件 {image_path} 出错: {str(e)}")

def batch_process_folder(folder_path):
    """批量处理文件夹内所有图像"""
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.lower().endswith(IMAGE_EXTENSIONS):
                image_path = os.path.join(root, file)
                calculate_image_stats(image_path)

class ImageFileHandler(FileSystemEventHandler):
    """监听文件夹内新增图像文件的处理器"""
    def on_created(self, event):
        if not event.is_directory and event.src_path.lower().endswith(IMAGE_EXTENSIONS):
            print("检测到新图像文件,开始计算...")
            calculate_image_stats(event.src_path)

def start_monitoring(folder_path):
    """启动文件夹监听"""
    event_handler = ImageFileHandler()
    observer = Observer()
    observer.schedule(event_handler, folder_path, recursive=True)
    observer.start()
    print(f"开始监听文件夹: {folder_path}")
    try:
        while True:
            pass
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

if __name__ == "__main__":
    # 替换为你的目标文件夹路径
    TARGET_FOLDER = r"你要处理的文件夹路径"
    
    # 先批量处理现有图像
    print("开始批量处理现有图像...")
    batch_process_folder(TARGET_FOLDER)
    
    # 启动持续监听
    start_monitoring(TARGET_FOLDER)

使用说明

  1. 将代码中的TARGET_FOLDER替换为你需要处理的文件夹路径
  2. 运行代码后,会先处理文件夹内已有的所有图像,随后持续监听文件夹,新加入的图像会自动被计算
  3. 按Ctrl+C可终止程序运行

内容的提问来源于stack exchange,提问作者Neko Lim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 22:10:35