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

如何基于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 returns None, so sorted_imgs is actually empty. Use sorted(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 shutil to 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

  1. Direct Filename Tracking: We store the actual filename alongside its width, so there's no confusion about which image corresponds to which width value.
  2. Proper Sorting: Uses sorted() instead of list.sort() to get a valid sorted list of images.
  3. Error Prevention: Checks for valid image files and ensures images load successfully before processing.
  4. Automatic Folder Creation: Uses os.makedirs(..., exist_ok=True) to create the target folder if it doesn't exist.
  5. 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_folder is different from source_folder to avoid overwriting files.
  • Ensure you have read/write permissions for both folders.
  • Adjust the width_threshold and folder paths to match your specific needs.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:18:32