IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    使用 Python 脚本实现图片相似度匹配

    Teacher Du发表于 2025-05-09 09:40:03
    love 0

    随着相机像素越来越大,图片体积也变大了。在图片处理中,较大的文件体积会影响性能,因此杜老师会先生成缩略图,筛选完成后再通过 Python 脚本实现图片相似度匹配。这里是一个简单的示例,供需要的小伙伴们参考。

    脚本说明

    以下是个基于 Python 的脚本,使用 PIL 以及 imagehash 库来实现。

    遍历目录 A 中所有图片。

    在目录 B 中查找相似的图片「通过感知哈希算法判断」

    如找到匹配项,则将图片复制到目录 C,并以目录 A 图片的名字命名。

    脚本代码

    在运行脚本前,需安装所需的 Python 库:

    1
    pip install pillow imagehash

    将 dir_a, dir_b 和 dir_c 替换为实际路径;threshold 控制图像相似度阈值,可以根据需要调整;支持多种常见格式图片文件;使用 imagehash.phash 进行感知哈希的比较,适合用于识别视觉上接近的图片:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    import os
    import shutil
    from PIL import Image
    import imagehash

    # 定义目录路径
    dir_a = 'path/to/dirA'
    dir_b = 'path/to/dirB'
    dir_c = 'path/to/dirC'

    # 设置相似度阈值(越小越严格)
    threshold = 5

    # 获取图片的感知哈希值
    def get_image_hash(filepath):
    try:
    return imagehash.phash(Image.open(filepath))
    except Exception as e:
    print(f"无法处理文件 {filepath}: {e}")
    return None

    # 判断两个哈希值是否相似
    def is_similar(hash1, hash2):
    return hash1 - hash2 <= threshold

    # 确保目标目录存在
    os.makedirs(dir_c, exist_ok=True)

    # 遍历目录 A
    for filename in os.listdir(dir_a):
    file_a_path = os.path.join(dir_a, filename)

    # 检查是否为图片
    if not filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
    continue

    hash_a = get_image_hash(file_a_path)
    if hash_a is None:
    continue

    # 遍历目录 B 寻找相似图片
    for b_filename in os.listdir(dir_b):
    file_b_path = os.path.join(dir_b, b_filename)

    # 检查是否为图片
    if not b_filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
    continue

    hash_b = get_image_hash(file_b_path)
    if hash_b is None:
    continue

    if is_similar(hash_a, hash_b):
    # 构建目标路径
    file_c_path = os.path.join(dir_c, filename)
    # 复制并重命名文件
    shutil.copy(file_b_path, file_c_path)
    print(f"已找到匹配: {filename} -> {b_filename}, 已复制到 {file_c_path}")


沪ICP备19023445号-2号
友情链接