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

Python新手求助:自动遍历文件夹图片,仅满足函数条件时执行处理

解决自动遍历图片并条件化处理的问题

Hey there! As a fellow Python developer, let's walk through how to tackle your problem step by step—since you're new to this, I'll keep things clear and actionable.

第一步:自动遍历文件夹里的图片文件

首先,我们完全不需要手动输入路径,Python自带的工具就能帮我们自动扫描文件夹。我推荐用pathlib(Python 3.4+内置),它比传统的os模块更直观好懂。

这里是获取指定文件夹下所有图片的代码:

from pathlib import Path

# 指定你的目标文件夹路径,比如当前目录下的"images"文件夹
image_folder = Path("./images")

# 遍历所有常见图片格式的文件(可根据需要添加更多格式,比如.bmp/.gif)
image_paths = (
    list(image_folder.glob("*.jpg"))
    + list(image_folder.glob("*.png"))
    + list(image_folder.glob("*.jpeg"))
)

# 现在image_paths里就是所有图片的路径对象了,逐个处理非常方便

如果你的图片分散在子文件夹里,把glob换成rglob就能递归扫描所有子目录:

image_paths = (
    list(image_folder.rglob("*.jpg"))
    + list(image_folder.rglob("*.png"))
)

第二步:完善compare_images函数

你提到正在编写compare_images,首先得明确这个函数的核心逻辑——比如是对比两张图片的相似度?还是和一张基准图匹配?我给你两个常见的实用示例:

先安装必要依赖(如果没装的话):

pip install pillow scikit-image

示例1:简单像素对比(判断两张图片是否几乎一致)

from PIL import Image
import numpy as np

def compare_images(img_path1, img_path2):
    # 打开图片并统一转成RGB格式(避免透明通道干扰)
    img1 = Image.open(img_path1).convert("RGB")
    img2 = Image.open(img_path2).convert("RGB")
    
    # 尺寸不一致直接返回不匹配
    if img1.size != img2.size:
        return False
    
    # 转成numpy数组计算像素差异比例
    arr1 = np.array(img1)
    arr2 = np.array(img2)
    diff_ratio = np.mean(arr1 != arr2)
    
    # 差异小于1%就认为满足条件,阈值可以自己调整
    return diff_ratio < 0.01

示例2:用SSIM判断视觉相似度(更贴合人眼感知)

from skimage.metrics import structural_similarity as ssim
from PIL import Image
import numpy as np

def compare_images(img_path, benchmark_img_path):
    # 转灰度图减少计算量(也可以保留RGB,调整ssim的channel参数)
    img = Image.open(img_path).convert("L")
    benchmark_img = Image.open(benchmark_img_path).convert("L")
    
    # 尺寸不一致的话先统一大小
    if img.size != benchmark_img.size:
        img = img.resize(benchmark_img.size)
    
    arr1 = np.array(img)
    arr2 = np.array(benchmark_img)
    
    # SSIM值范围是[-1,1],越接近1越相似,这里设阈值为0.8
    ssim_score = ssim(arr1, arr2)
    return ssim_score > 0.8

第三步:整合流程——遍历+判断+执行操作

现在把两部分结合起来,实现“自动遍历图片,只有当compare_images返回True时才执行操作”:

from pathlib import Path
from PIL import Image
import numpy as np

# 先定义你的compare_images函数(选上面的一个,或者自定义逻辑)
def compare_images(img_path, benchmark_img_path):
    img = Image.open(img_path).convert("L")
    benchmark_img = Image.open(benchmark_img_path).convert("L")
    
    if img.size != benchmark_img.size:
        img = img.resize(benchmark_img.size)
    
    arr1 = np.array(img)
    arr2 = np.array(benchmark_img)
    
    from skimage.metrics import structural_similarity as ssim
    ssim_score = ssim(arr1, arr2)
    return ssim_score > 0.8

# 定义你要执行的操作(比如保存到新文件夹、修改图片等)
def perform_action(img_path):
    print(f"Processing {img_path.name}...")
    # 这里写你的具体操作,示例:
    # img = Image.open(img_path)
    # img.save(f"./processed_images/{img_path.name}")

def main():
    # 目标图片文件夹
    image_folder = Path("./images")
    # 基准图片路径(如果你的对比逻辑是和基准图比的话)
    benchmark_path = Path("./reference_photo.jpg")
    
    # 获取所有图片路径
    image_paths = (
        list(image_folder.glob("*.jpg"))
        + list(image_folder.glob("*.png"))
    )
    
    for img_path in image_paths:
        # 调用判断函数,满足条件就执行操作
        if compare_images(img_path, benchmark_path):
            perform_action(img_path)
        else:
            print(f"Skipping {img_path.name} - condition not met")

if __name__ == "__main__":
    main()

一些额外小提示

  • 如果你的compare_images是对比当前图片和前一张(比如逐张序列对比),只需要在遍历的时候保存上一张的路径,传入函数即可。
  • 记得加异常处理:比如图片损坏无法打开,用try-except包裹Image.open的代码,避免程序崩溃。
  • 可以根据需求扩展图片格式,比如添加.gif、.webp等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:30:33