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

如何遍历目录及子目录计算单张图片平均强度?现有单目录代码需扩展

Solution for Recursive Image Average Intensity Calculation

Got it, let's update your code to handle nested directories and keep track of images with low average intensity. Here's the revised version with key improvements explained:

from skimage import io, img_as_float
import matplotlib.image as mpimg
import os
import pandas as pd
import numpy as np  # Added since you're using np.mean()

def load_images(root_folder):
    data = []
    # Use os.walk to recursively traverse all subdirectories
    for dirpath, _, filenames in os.walk(root_folder):
        for filename in filenames:
            # Skip non-image files (optional but recommended)
            if not filename.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif')):
                continue
            img_path = os.path.join(dirpath, filename)
            try:
                img = mpimg.imread(img_path)
                img = img_as_float(img)
                avg_intensity = np.mean(img)
                # Check if average intensity is below threshold
                if avg_intensity < 0.1:
                    print(f"Low intensity image found: {img_path}")
                    data.append((dirpath, filename, avg_intensity))  # Added intensity value for reference
            except Exception as e:
                print(f"Error processing {img_path}: {str(e)}")
                continue
    # Create DataFrame with folder, filename, and average intensity
    df = pd.DataFrame(data, columns=['Folder', 'File', 'Average Intensity'])
    return df

# Example usage
df = load_images("/path/to/your/root/directory")
# Optional: Save results to CSV
df.to_csv("low_intensity_images.csv", index=False)

Key Changes & Explanations:

  • Recursive Directory Traversal: Replaced os.listdir() with os.walk(), which iterates through every subdirectory under the root folder. dirpath gives the full path to the current directory being processed.
  • File Filtering: Added a check to skip non-image files (you can adjust the extensions list to match your needs) to avoid errors from trying to load non-image files.
  • Error Handling: Wrapped image loading in a try-except block to handle cases where a file might be corrupted or not a valid image—this prevents the script from crashing mid-run.
  • Enhanced Data Tracking: Added the actual average intensity value to the DataFrame for better context, instead of just folder and filename.
  • Fixed Dependency: Added import numpy as np since your original code uses np.mean() but didn't import NumPy.

This script will now process every image in your target directory and all its subdirectories, log any low-intensity images, and return a structured DataFrame with the results. You can also save the DataFrame to a CSV file for later analysis, as shown in the example.

内容的提问来源于stack exchange,提问作者Zephyr India

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:35:35