以下是个基于 Python 的脚本,使用 PIL 以及 imagehash 库来实现。
遍历目录 A 中所有图片。
在目录 B 中查找相似的图片「通过感知哈希算法判断」
如找到匹配项,则将图片复制到目录 C,并以目录 A 图片的名字命名。
安装依赖
1
|
pip install pillow imagehash
|
注意:在运行脚本前,需安装所需的 Python 库。
脚本示例
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}") |
注意:将 dir_a, dir_b 和 dir_c 替换为实际路径;threshold 控制图像相似度阈值,可以根据需要调整;支持多种常见格式图片文件;使用 imagehash.phash 进行感知哈希的比较,适合用于识别视觉上接近的图片。
运行效果
1 2 3 4 5 |
(myenv) penn@penn-VMware-Virtual-Platform:~/图片$ python3 1.py 已找到匹配: image105.jpg -> 1745928332994.jpg, 已复制到 c/image105.jpg 已找到匹配: image001.jpg -> 1745736425856.jpg, 已复制到 c/image001.jpg 已找到匹配: image017.jpg -> 1745736425221.jpg, 已复制到 c/image017.jpg 已找到匹配: image085.jpg -> 1745928334851.jpg, 已复制到 c/image085.jpg |
注意:脚本运行过程可能会有错误提示,需要根据提示进行修复。
小林博客





