如何基于img.shape获取的宽度值将图片批量移动至指定文件夹?
Fixing Your Image Sorting & Moving Issue
Let's work through this problem step by step — the core issue here is that your current code uses index numbers instead of actual filenames to track image widths, which is why you can't map back to the original files. Here's how to adjust your code to directly link filenames to their widths, then move the qualifying images:
Key Issues in Your Existing Code
sorted_imgs = imgs.sort(...)doesn't work as expected:list.sort()modifies the list in-place and returnsNone, sosorted_imgsis actually empty. Usesorted(imgs, key=...)to get a valid sorted list instead.- You're storing indexes instead of filenames in your key-value pairs, breaking the link to actual image files.
- You're missing a tool like
shutilto handle file moves (we'll add this in the fixed code).
Fixed Code with Explanations
This version generates a (filename, width) list, filters by your threshold, and moves the images to your target folder:
import os import cv2 import shutil # Configure your parameters here source_folder = os.path.expanduser('~\\Desktop\\roiseparator\\roi_single\\') target_folder = os.path.expanduser('~\\Desktop\\roiseparator\\width_under_50\\') # Update this path width_threshold = 50 # Adjust this threshold as needed # Create target folder if it doesn't exist (avoids path errors) os.makedirs(target_folder, exist_ok=True) # Get sorted list of images (sorted by the numeric prefix in filenames) sorted_images = sorted(os.listdir(source_folder), key=lambda x: int(x.split('.')[0])) # Build a list of (filename, width) pairs image_width_data = [] for img_filename in sorted_images: # Skip non-image files to prevent errors (optional but recommended) if not img_filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')): continue img_path = os.path.join(source_folder, img_filename) image = cv2.imread(img_path) # Only process if the image was successfully loaded if image is not None: height, width = image.shape[:2] image_width_data.append((img_filename, width)) # Filter images where width is <= threshold qualifying_images = [filename for filename, w in image_width_data if w <= width_threshold] # Move the qualifying images to the target folder for filename in qualifying_images: source_path = os.path.join(source_folder, filename) target_path = os.path.join(target_folder, filename) shutil.move(source_path, target_path) print(f"Moved: {filename}") print(f"Completed! Moved {len(qualifying_images)} images to {target_folder}")
Key Improvements
- Direct Filename Tracking: We store the actual filename alongside its width, so there's no confusion about which image corresponds to which width value.
- Proper Sorting: Uses
sorted()instead oflist.sort()to get a valid sorted list of images. - Error Prevention: Checks for valid image files and ensures images load successfully before processing.
- Automatic Folder Creation: Uses
os.makedirs(..., exist_ok=True)to create the target folder if it doesn't exist. - Simplified Logic: Removed unnecessary intermediate lists (
lista_roi,lista_w) to make the code cleaner and easier to follow.
Quick Notes
- Make sure your
target_folderis different fromsource_folderto avoid overwriting files. - Ensure you have read/write permissions for both folders.
- Adjust the
width_thresholdand folder paths to match your specific needs.
内容的提问来源于stack exchange,提问作者lucians
相关产品推荐
相关产品推荐

