如何批量扫描图片文件夹,基于图像均值识别暗图
Batch Filtering of Dark Images in a Folder
I see you already have the core logic to detect dark images using the mean pixel value—great start! Let's expand that into a full batch processing script that scans your entire folder, identifies dark images, and lets you handle them (like logging their paths or moving them to a separate directory).
Full Batch Processing Code
from skimage import io, img_as_float import numpy as np import os from glob import glob # Configuration - adjust these paths and thresholds to your needs IMAGE_FOLDER = "C:/Data/Testing" DARK_IMAGE_THRESHOLD = 0.1 # Optional: Create a folder to move dark images to (avoids accidental deletion) DARK_IMAGE_DEST = os.path.join(IMAGE_FOLDER, "dark_images") os.makedirs(DARK_IMAGE_DEST, exist_ok=True) # Get all image files in the folder (supports common formats; add more if needed) image_paths = glob(os.path.join(IMAGE_FOLDER, "*.jpg")) + glob(os.path.join(IMAGE_FOLDER, "*.png")) + glob(os.path.join(IMAGE_FOLDER, "*.jpeg")) # Iterate through each image for img_path in image_paths: try: # Load and preprocess the image (same as your single-image code) image = io.imread(img_path) image = img_as_float(image) mean_value = np.mean(image) # Classify the image if mean_value < DARK_IMAGE_THRESHOLD: print(f"Dark image detected: {img_path} (mean: {mean_value:.4f})") # Optional: Move the dark image to the dedicated folder os.rename(img_path, os.path.join(DARK_IMAGE_DEST, os.path.basename(img_path))) else: print(f"Normal image: {img_path} (mean: {mean_value:.4f})") except Exception as e: print(f"Error processing {img_path}: {str(e)}")
Key Details Explained
- Folder Traversal: We use
glob.glob()to target specific image formats (JPG, PNG, JPEG) instead of scanning all files—this avoids trying to process non-image files which would cause errors. - Error Handling: The
try-exceptblock catches issues like corrupted images or unsupported file types, so the script won't crash halfway through. - Organized Storage: The optional
dark_imagesfolder lets you segregate dark images instead of just logging them, which is safer than deleting them directly. - Configurable: You can easily adjust
IMAGE_FOLDER,DARK_IMAGE_THRESHOLD, or add more image formats to theglobcalls to match your setup.
Quick Notes
- If you don't want to move the images and just need a list of dark ones, comment out the
os.rename()line and instead append the paths to a text file for later reference. - For very large folders, consider adding a progress tracker (like using the
tqdmlibrary) to see how many images have been processed.
内容的提问来源于stack exchange,提问作者Zephyr India
相关产品推荐
相关产品推荐

