如何遍历目录及子目录计算单张图片平均强度?现有单目录代码需扩展
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()withos.walk(), which iterates through every subdirectory under the root folder.dirpathgives 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-exceptblock 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 npsince your original code usesnp.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
相关产品推荐
相关产品推荐

